How does the try catch finally block work?

若如初见. 提交于 2019-12-09 05:04:19

问题


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?


回答1:


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




回答2:


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.




回答3:


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;
        }
    }



回答4:


        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");
        }


来源:https://stackoverflow.com/questions/13545230/how-does-the-try-catch-finally-block-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!