How Can I Force Execution to the Catch Block?

后端 未结 12 1225
野趣味
野趣味 2021-01-17 07:46

I am wondering can try..catch force execution to go into the catch and run code in there?

here example code:

try {
    if (         


        
12条回答
  •  一向
    一向 (楼主)
    2021-01-17 08:08

    I think what you want is a finally block: http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx

    see this

    try
     {
         doSomething();
     }
    catch
     {
         catchSomething();
         throw an error
     } 
    finally
     {
         alwaysDoThis();
     }
    

    This is different if/when you do this:

    try
     {
         doSomething(); 
     }
     catch
     {
         catchSomething(); 
         throw an error
     }
      alwaysDoThis();// will not run on error (in the catch) condition
    

    the the this last instance, if an error occurs, the catch will execute but NOT the alwaysDoThis();. Of course you can still have multiple catch as always.

提交回复
热议问题