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?
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.
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.
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.
Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.
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).
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