views:

115

answers:

4

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

+10  A: 

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.

Oded
i thing that try catch is a better then it are i am right
4thpage
What do you mean by "better"? The `finally` block has specific use cases. Sometimes you need it, sometimes you don't.
Oded
@4thpage Media and services: It depends on whether you have objects that you want to clear up whether an exception happens or not.
Ardman
As @ho1 mentioned, you are not required to have a catch when using the finally
Dave White
+5  A: 

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.

ho1
A: 

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

Dal
+1  A: 

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.

Hinek