Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching Exception inside Using statement

Tags:

I know that Using statement disposes out the object that is being created. Like if I wanted to do something like this:

    Using(SqlConnection conn = new SqlConnection(connString))     {       //some code       //How to show the users if conn is not opened up or generated some kind of error?     } 

How to show the users if conn is not opened up or generated some kind of error?

like image 596
RG-3 Avatar asked Apr 17 '12 14:04

RG-3


People also ask

Does With statement support exception handling?

What do you mean "enclosing 'with' in a try/except statement doesn't work else: exception is not raised"? A with statement doesn't magically break a surrounding try... except statement. Interestingly, Java's try-with-resources statement does support exactly this use case you want.

How do you write Catch exception?

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.

Does using dispose if exception?

MSDN using documentation also confirms this answer: The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

Can we use try-catch inside using?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.


1 Answers

There's nothing special about code written inside a using block - just use a try.catch to handle exceptions:

using(SqlConnection conn = new SqlConnection(connString)) {     try     {         conn.Open();         // do more stuff here......      }     catch(SqlException sqlEx)     {        // log error and possibly show to user in a MessageBox or something else     } } 

The using(...) { ... } block itself is designed only to ensure that the resource / object it "encapsulates" is properly disposed of when it's no longer needed. There's is nothing you can do with the using statement itself to make it handle errors.

So if you expect that just creating the object could fail, then you'd have to put the entire using block inside the try ... catch block , or fall back to a try ... catch ... finally block and ensure proper disposal yourself (as Adam suggested in his answer).

like image 52
marc_s Avatar answered Jan 09 '23 17:01

marc_s