if i want to use
try
{
}
catch(exception ex)
{
}
how i can use try finally method where i use try catch
who is better any one specific on both
if i want to use
try
{
}
catch(exception ex)
{
}
how i can use try finally method where i use try catch
who is better any one specific on both
This is how finally
is used:
try
{
}
catch(exception ex)
{
}
finally
{
}
finally
is not instead of catch
- it is supplementary to it. You use it with catch
, when you need to cleanup resources.
You use the finally
block when you want to clean out resources that need cleaning out whether an exception was thrown in the try block or not.
From the C# Reference:
A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.
As the tag you've selected indicates, you can use catch and finally at the same time, it's not an either/or situation.
So this is ok:
try
{
}
catch(SomeEx ex)
{
}
finally
{
}
But you can leave out either of the catch
or finally
statements if you have no use for them.
Though I'd suggest that when possible you should try to use using
statements instead of finally.
My understanding is that the finally block is entirely optional but if you do include it in your code it will always be executed, even in the event of an exception occurring.
http://msdn.microsoft.com/en-us/library/dszsf989%28VS.71%29.aspx
You can use try + catch if you want to catch and handle exceptions (i.e. write them to a log, show the user a message):
try {}
catch (FileNotFoundException)
{
// show message: file could not be found
}
Or you can use try + finally if you have to do something in any case (if the stuff in try was successful or not):
Stream stream = ...
try {}
finally
{
stream.Close();
}
And you can even use both, if you need.
Stream stream = ...
try {}
catch (IOException ex)
{
log.Write(ex.ToString());
}
finally
{
stream.Close();
}
There isn't one better than the other, they are used for different jobs.