Try catch finally: Do something if no exception is thrown

Sure there is: put it at the bottom of the try block.

try{
    // something
    // i can do what i want here
}catch(Exception e){
    // handle exception
}

This is not entirely equivalent to your original code in the sense that if "what you want" throws, the exception will be caught locally (this would not happen with your original scheme). This is something you might or might not care about, and there's a good chance that the different behavior is also the correct one.

If you want to bring the old behavior back, you can also use this variant that doesn't require a finally just for the sake of writing the "if no exceptions" condition:

var checkpointReached = false;
try{
    // something
    checkpointReached = true;
    // i can do what i want here
}catch(Exception e){
    if (checkpointReached) throw; // don't handle exceptions after the checkpoint
    // handle exception
}

Yes there is: put it at the end of the try block :)


Can you structure your code that the doSomething is the last statement in the block and it doesn't throw?

bool exception = false;
try{
  // something
  doSomething();
} catch {
}
finally {
}

You don't need the finally clause.

A solution :

bool exception = false;
try{
    // something
}catch(Exception e){
    exception = true;
}
if(!exception){
     // u can do what u want here
} 

Usually you'll simply have a return in your catch clause so that you don't even have to test :

try{
    // something
}catch(Exception e){
   // do things
   return;
}
// u can do what u want here

or (depending on the use case and generally less clear, especially if you have more than one exception expected - you don't want to have try-catch nesting...) :

try{
    // something
    // u can do what u want here
}catch(Exception e){
   // do things
}

Tags:

C#

Try Catch