Why does this “finally” execute?

前端 未结 8 935
故里飘歌
故里飘歌 2020-12-14 19:02

If you run the code below it actually executes the finally after every call to the goto:

    int i = 0;
Found:
    i++;
    try
    {
        throw new Exc         


        
8条回答
  •  余生分开走
    2020-12-14 19:24

    Why do you expect it to not execute?

    If you have try/catch/finally or try/finally block, finally block executes no matter what code you may have in the try or catch block most of the time.

    Instead of goto, consider 'return'.

    //imagine this try/catch/finally block is inside a function with return type of bool. 
    try
    {
        throw new Exception();
    }
    catch (Exception)
    {
        return false; //Let's say you put a return here, finally block still executes.
    }
    finally
    {
        Console.WriteLine("I am in finally!");
    }
    

提交回复
热议问题