C#: "using" directive and try/catch block - c#

I know how to use try/catch block in case of database calls and know how to use "using" directive in context of using try/finally construction as well.
But, can I mix them? I mean when I use "using" directive can I use try/catch construction as well because I still need to handle possible errors?

You can definitely use both together.
A using block is basically just a bit of syntactic sugar for a try/finally block and you can nest try/finally blocks if you wish.
using (var foo = ...)
{
// ...
}
Is roughly equivalent to this:
var foo = ...;
try
{
// ...
}
finally
{
foo.Dispose();
}

Of course you can do it:
using (var con = new SomeConnection()) {
try {
// do some stuff
}
catch (SomeException ex) {
// error handling
}
}
using is translated by the compiler into a try..finally, so it's not very different from nesting a try..catch inside a try..finally.

This one is perfectly valid:
using (var stream = new MemoryStream())
{
try
{
// Do something with the memory stream
}
catch(Exception ex)
{
// Do something to handle the exception
}
}
The compiler would translate this into
var stream = new MemoryStream();
try
{
try
{
// Do something with the memory stream
}
catch(Exception ex)
{
// Do something to handle the exception
}
}
finally
{
if (stream != null)
{
stream.Dispose();
}
}
Of course this nesting works the other way round as well (as in nesting a using-block within a try...catch-block.

A using such as:
using (var connection = new SqlConnection())
{
connection.Open
// do some stuff with the connection
}
is just a syntactic shortcut for coding something like the following.
SqlConnection connection = null;
try
{
connection = new SqlConnection();
connection.Open
// do some stuff with the connection
}
finally
{
if (connection != null)
{
connection.Dispose()
}
}
This means, yes, you can mix it with other try..catch, or whatever. It would just be like nesting a try..catch in a try..finally.
It is only there as a shortcut to make sure the item you are "using" is disposed of when it goes out of scope. It places no real limitation on what you do inside the scope, including providing your own try..catch exception handling.

Related

Try-Catch within Using()

My code is currently
using(var driver = new driver()){something}
And I want to be able to catch exceptions. However I only want to catch exceptions thrown by "driver = new driver". Looking online I can find how to catch exceptions thrown by the whole thing or by "something" but I cannot work out how to put a try-catch into the "using" parameter.
It's a very strange requirement, but whatever that's your call.
You should get rid of the using completely, and handle the dispose yourself (which has the same result).
This is what you want:
driver driver = null;
try
{
try
{
driver = new driver();
}
catch(Exception ex)
{
// Here is your specific exception.
}
// Do something
}
finally
{
if(driver != null)
driver.Dispose();
}
Just do it:
Driver driver = null;
try
{
driver = new Driver();
}
catch()
{
// do whatever, throw, fail, return...
}
// if you did not break out of your logic in the catch (why not?)
// add an if(driver != null) before you proceed
using(driver)
{
// something
}
You can add a method to construct your driver and put your try/catch in there:
private static Driver CreateDriver()
{
try
{
return new Driver();
}
catch(Exception ex)
{
// whatever other exception handling you want
return null;
}
}
using(var driver = CreateDriver())
{
// something
}
Of course, if you do this, when your something code is executing inside the using block, driver may be null, so you'll need to check for this, e.g.:
using(var driver = CreateDriver())
{
if (driver != null)
{
// something
}
}
The "using" clause, primarily function is to dispose managed code resources once the process inside the clause has been completed. It "hides" a try catch block inside it, but if you really want to handle errors, you need to do it yourself.
eg.
Try
{
//do stuff
}
catch (exception ex)
{
//handle exception
//resource.Dispose();
}
After you handle your exceptions, you should dispose the unused resources by calling .Dispose(), assuming that the latter is a managed code resource and encapsulates the IDisposable interface

Are using gonna close connection if it fails?

I am intrested if i use using (that close all connection) inside try catch
try{
using (var browser = new IE("https://www.bbvanetcash.com/local_kyop/KYOPSolicitarCredenciales.html"))
{
clsUtils.WriteToLog("Trying to login", true, true);
browser.Visible = false;
browser.TextField(Find.ByName("cod_emp")).Value = _company;
browser.TextField(Find.ByName("cod_usu")).Value = _strUser;
browser.TextField(Find.ByName("eai_password")).Value = _strPass;
browser.Button(Find.ByClass("grandote estirado azul")).Click();
browser.WaitForComplete();
clsUtils.WriteToLog("Logged ", true, true);
connected = true;
var cookie = browser.Eval("document.cookie");
CookieContainer Cc = GetCc(cookie);
} catch (Exception ex)
{
Console.WriteLine("(TryToLogin)-->Catching the {0} exception .", ex.GetType());
return connected;
}
}
and if one of steps gona fail the using gonna close the connection or it just gona go to catch?
MSDN:
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Disposein a finally block; in fact, this is how the using statement is translated by the compiler.
yes it does, if you are using a using statement i has to implement the Idispose class.
so if you are using something like below
using (foo)
{
//...
}
the compiler will interpret like below.
try
{
//...
}
finally
{
foo.Dispose();
}
hope this helps.

nested using statements - which one wont get disposed

If i have some code like this and an error occurs in the second using statement, will the dispose method on 1st using not be called?
using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(cnstr))
{
cn.Open();
using (SqlTransaction tran = cn.BeginTransaction(IsolationLevel.Serializable))
{
--EDIT--
Also is it better to write Try / Finally block or using statement. Internally compilter will generate Try / Finally for using statement but as per coding standards which one is better?
No, both will be called. Just because an exception is called in the inner statement, doesn't mean that the first is ignored.
a using statement is just another syntax for:
var iDisposableItem = new Item();
try
{
......
}
finally
{
iDisposableItem.Dispose();
}
so in your example:
var iDisposableItem = new Item();
try
{
var iDisposableItem2 = new Item();
try
{
throws exception
}
finally
{
iDisposableItem2 .Dispose();
}
}
finally
{
iDisposableItem.Dispose();
}
Now what should be noted and what you have to be careful about is that whatever caused the first exception could cause problems with the outer using statement when it calls Dispose(). The exception could throw the (really either) object into a faulted state and calling Dispose might result in another different exception which "masks" the first one. This is a gotcha in WFC when using using statements: http://msdn.microsoft.com/en-us/library/aa355056.aspx
A using statement is nothing but a try/finally in disguise, unless the process is forcibly terminated, your objects will be disposed of correctly.
In other words, this:
using (Type1 x = new Type1())
{
// a
using (Type2 y = new Type2())
{
// b
}
// c
}
Is actually similar to this (this is simplified):
Type1 x = new Type1();
try
{
// a
Type2 y = new Type2();
try
{
// b
}
finally
{
y.Dispose();
}
// c
}
finally
{
x.Dispose();
}
It will dispose both, and you can shorten it like:
using (SqlConnection cn = new SqlConnection(cnstr), SqlTransaction tran = cn.BeginTransaction(IsolationLevel.Serializable))
{
cn.Open();
}

Where the finally is necessary?

I know how to use try-catch-finally. However I do not get the advance of using finally as I always can place the code after the try-catch block.
Is there any clear example?
It's almost always used for cleanup, usually implicitly via a using statement:
FileStream stream = new FileStream(...);
try
{
// Read some stuff
}
finally
{
stream.Dispose();
}
Now this is not equivalent to
FileStream stream = new FileStream(...);
// Read some stuff
stream.Dispose();
because the "read some stuff" code could throw an exception or possibly return - and however it completes, we want to dispose of the stream.
So finally blocks are usually for resource cleanup of some kind. However, in C# they're usually implicit via a using statement:
using (FileStream stream = new FileStream(...))
{
// Read some stuff
} // Dispose called automatically
finally blocks are much more common in Java than in C#, precisely because of the using statement. I very rarely write my own finally blocks in C#.
You need a finally because you should not always have a catch:
void M()
{
var fs = new FileStream(...);
try
{
fs.Write(...);
}
finally
{
fs.Close();
}
}
The above method does not catch errors from using fs, leaving them to the caller. But it should always close the stream.
Note that this kind of code would normally use a using() {} block but that is just shorthand for a try/finally. To be complete:
using(var fs = new FileStream(...))
{
fs.Write(...);
} // invisible finally here
try
{
DoSomethingImportant();
}
finally
{
ItIsRidiculouslyImportantThatThisRuns();
}
When you have a finally block, the code therein is guaranteed to run upon exit of the try. If you place code outside of the try/catch, that is not the case. A more common example is the one utilized with disposable resources when you use the using statement.
using (StreamReader reader = new StreamReader(filename))
{
}
expands to
StreamReader reader = null;
try
{
reader = new StreamReader(filename);
// do work
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
This ensures that all unmanaged resources get disposed and released, even in the case of an exception during the try.
*Note that there are situations when control does not exit the try, and the finally would not actually run. As an easy example, PowerFailureException.
Update: This is actually not a great answer. On the other hand, maybe it is a good answer because it illustrates a perfect example of finally succeeding where a developer (i.e., me) might fail to ensure cleanup properly. In the below code, consider the scenario where an exception other than SpecificException is thrown. Then the first example will still perform cleanup, while the second will not, even though the developer may think "I caught the exception and handled it, so surely the subsequent code will run."
Everybody's giving reasons to use try/finally without a catch. It can still make sense to do so with a catch, even if you're throwing an exception. Consider the case* where you want to return a value.
try
{
DoSomethingTricky();
return true;
}
catch (SpecificException ex)
{
LogException(ex);
return false;
}
finally
{
DoImportantCleanup();
}
The alternative to the above without a finally is (in my opinion) somewhat less readable:
bool success;
try
{
DoSomethingTricky();
success = true;
}
catch (SpecificException ex)
{
LogException(ex);
success = false;
}
DoImportantCleanup();
return success;
*I do think a better example of try/catch/finally is when the exception is re-thrown (using throw, not throw ex—but that's another topic) in the catch block, and so the finally is necessary as without it code after the try/catch would not run. This is typically accomplished with a using statement on an IDisposable resource, but that's not always the case. Sometimes the cleanup is not specifically a Dispose call (or is more than just a Dispose call).
The code put in the finally block is executed even when:
there are return statements in the try or catch block
OR
the catch block rethrows the exception
Example:
public int Foo()
{
try
{
MethodThatCausesException();
}
catch
{
return 0;
}
// this will NOT be executed
ReleaseResources();
}
public int Bar()
{
try
{
MethodThatCausesException();
}
catch
{
return 0;
}
finally
{
// this will be executed
ReleaseResources();
}
}
you don't necessarily use it with exceptions. You may have try/finally to execute some clean up before every return in the block.
The finally block always is executed irrespective of error obtained or not. It is generally used for cleaning up purposes.
For your question, the general use of Catch is to throw the error back to caller, in such cases the code is finally still executes.
The finally block will always be executed even if the exception is re-thrown in the catch block.
If an exception occurs (or is rethrown) in the catch-block, the code after the catch won't be executed - in contrast, code inside a finally will still be executed.
In addition, code inside a finally is even executed when the method is exited using return.
Finally is especially handy when dealing with external resources like files which need to be closed:
Stream file;
try
{
file = File.Open(/**/);
//...
if (someCondition)
return;
//...
}
catch (Exception ex)
{
//Notify the user
}
finally
{
if (file != null)
file.Close();
}
Note however, that in this example you could also use using:
using (Stream file = File.Open(/**/))
{
//Code
}
For example, during the process you may disable WinForm...
try
{
this.Enabled = false;
// some process
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.Enabled = true;
}
I am not sure how it is done in c#, but in Delphi, you will find "finally" very often. The keyword is manual memory management.
MyObject := TMyObject.Create(); //Constructor
try
//do something
finally
MyObject.Free();
end;

Can you catch in a using block?

Can exceptions be caught inside a using block, and if so what is the syntax?
So, something like the following:
using (var creatingThing = new MyCreatingThing())
{
creatingThing.CreateSomething();
catch()
{
creatingThing.Rollback();
}
}
Can this be done? Or do I need to write this code manually (ie without a using)?
You can put a try/catch inside the using statement, or outside:
using (...)
{
try
{
...
}
catch
{
...
}
}
Or...
try
{
using (...)
{
...
}
}
catch
{
...
}
However, you can't just put a catch block without a try block.
Choose the right one based on what whether you need to catch exceptions which are thrown by the resource acquisition expression, whether you want the resource to be disposed before your catch block is executed, and whether you need access to the resource variable within the catch block.
You cannot implicitly enlist in the try...finally block that the compiler generates (for the using statement). You have to add another try statement, which will be nested within the generated block:
using (var creatingThing = new MyCreatingThing())
{
try
{
creatingThing.CreateSomething();
}
catch
{
creatingThing.Rollback();
}
}
Note, the a using is really a try/finally under the covers, so it may be easier the code it that way:
MyCreatingThing creatingThing = null;
try
{
creatingThing = new MyNCreatingThing())
creatingThing.CreateSomething();
}
catch()
{
Console.WriteLine("An Exception happened");
if (creatingThing !=null)
creatingThing.Rollback();
}
finally
{
if (creatingThing !=null)
creatingThing.Dispose();
}
Sure, just add the try inside the using:
using (var creatingThing = new MyCreatingThing())
{
try
{
creatingThing.CreateSomething();
}
catch(Exception ex)
{
creatingThing.Rollback();
}
}

Categories