How does the try catch finally block work?

2020-05-29 13:05发布

In C#, how does a try catch finally block work?

So if there is an exception, I know that it will jump to the catch block and then jump to the finally block.

But what if there is no error, the catch block wont get run, but does the finally block get run then?

4条回答
SAY GOODBYE
2楼-- · 2020-05-29 13:15
        try
        {
            //Function to Perform
        }
        catch (Exception e)
        {
         //You can display what error occured in Try block, with exact technical spec (DivideByZeroException)
            throw; 
            // Displaying error through signal to Machine, 
            //throw is usefull , if you calling a method with try from derived class.. So the method will directly get the signal                
        }

        finally  //Optional
        {
            //Here You can write any code to be executed after error occured in Try block
            Console.WriteLine("Completed");
        }
查看更多
姐就是有狂的资本
3楼-- · 2020-05-29 13:17

Yes, the finally block gets run whether there is an exception or not.

Try
    [ tryStatements ]
    [ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
    [ catchStatements ]
    [ Exit Try ] ]
[ Catch ... ]
[ Finally
    [ finallyStatements ] ] --RUN ALWAYS
End Try

See: http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx

查看更多
狗以群分
4楼-- · 2020-05-29 13:32

finally block always run , no matter what. just try this method

     public int TryCatchFinally(int a, int b)
    {
        try
        {
            int sum = a + b;
            if (a > b)
            {
                throw new Exception();
            }
            else
            {
                int rightreturn = 2;
                return rightreturn;
            }
        }
        catch (Exception)
        {
            int ret = 1;
            return ret;
        }
        finally
        {
            int fin = 5;
        }
    }
查看更多
别忘想泡老子
5楼-- · 2020-05-29 13:36

Yes the finally clause gets exeucuted if there is no exception. Taking an example

     try
        {
            int a = 10;
            int b = 20;
            int z = a + b;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            Console.WriteLine("Executed");
        }

So here if suppose an exception occurs also the finally gets executed.

查看更多
登录 后发表回答