Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch exceptions within a using block vs outside the using block - which is better?

Tags:

c#

c#-3.0

Is there any difference between these tow pieces of code & which approach is better.

try {     using()     {        //Do stuff     } } catch {     //Handle exception }   using() {     try     {          //Do stuff     }     catch     {         //Handle exception     } } 
like image 472
Kashif Avatar asked May 26 '09 16:05

Kashif


People also ask

Which block is useful to catch an exception?

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block. Each catch block is an exception handler that handles the type of exception indicated by its argument.

Which is the correct way to use catch block?

Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.

Is it bad practice to use try catch?

Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.

What happens if an exception is thrown outside a catch block?

If a catch block ends normally, without a throw , the flow of control passes over all other catch blocks associated with the try block. Whenever an exception is thrown and caught, and control is returned outside of the function that threw the exception, stack unwinding takes place.


2 Answers

There are differences, but it namely boils down to the fact that a using block creates it own try and scope blocks.

try {     using(IDisposable A = GetDisposable())     {        //Do stuff     } } catch {     //Handle exception     // You do NOT have access to A }   using(IDisposable A = GetDisposable())  //exception here is uncaught {     try     {          //Do stuff     }     catch     {         //Handle exception         // You DO have access to A     } } 
like image 56
Joel Coehoorn Avatar answered Oct 14 '22 17:10

Joel Coehoorn


There's a difference between these blocks. In the second case the exception won't be caught if it is thrown in the using() line (for example instantiating an IDisposable object and the constructor throws an exception). Which one is better will depend on your specific needs.

like image 42
Darin Dimitrov Avatar answered Oct 14 '22 18:10

Darin Dimitrov