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 } }
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.
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.
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.
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.
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 } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With