C# Language Reference
try-finally (C# Reference)

The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.

Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.

Example

In this example, there is one invalid conversion statement that causes an exception. When you run the program, you get a run-time error message, but the finally clause will still be executed and display the output.

C#
public class ThrowTest
{
    static void Main()
    {
        int i = 123;
        string s = "Some string";
        object o = s;

        try
        {
            // Invalid conversion; o contains a string not an int
            i = (int)o;
        }
        finally
        {
            Console.Write("i = {0}", i);
        }
    }
}

The example above causes System.InvalidCastException to be thrown.

Although an exception was caught, the output statement included in the finally block will still be executed, that is:

i = 123

For more information on finally, see try-catch-finally.

C# also provides the using statement which provides a convenient syntax for the exact same functionality as a try-finally statement.

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 5.3.3.14 Try-finally statements

  • 8.11 The try statement

  • 16 Exceptions

See Also

Tasks

Concepts

Reference

Other Resources

Tags :


Community Content

Thomas Lee
Wrong

This is totally wrong !

The application craches at runtime, as the InvalidCastException was not handled.


[tfl - 24.1.09]
This is due to no "Catch" block being specified. See example below (in PowerShell).
Tags : contentbug

Thomas Lee
definition also horrible

resources allocated in the try block huh?!?

[tfl 24-1-09]
Yes. You might have allocated some resourse, opened a file, etc in the try block. The Finally block allows you to clean up irrespective of an exception being caught.

Tags :

Thomas Lee
Try/Catch/Finally Sample, using PowerShell

<#
.SYNOPSIS
    Shows Try/Catch/Finally using Powershell
.DESCRIPTION
    This is an MSDN Sample, re-writin in PowerShell
.NOTES
    File Name  : get-trycatchfinally.ps1
    Author     : Thomas Lee - tfl@psp.co.uk
    Requires   : PowerShell V2 CTP3
.LINK
    Original script posted to:
    http://www.pshscripts.blogspot.com
     MSDN Sample at:
     http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
.EXAMPLE
    PS C:\foo> .\Get-TryCatchFinally.ps1
    Error in conversion
    Error record: Cannot convert value "Some string" to type "System.Int32". Error: "Input string was not in a correct format."
    $i = 123
    $i = System.Int32
#>





###
# Start of script
###




# Create some explicity typed values
[int] $i = 123
[string] $s = "Some string"
[object] $o = $s
# Now try to convert an object into an integer (which will fail)try {
# Invalid conversion; o contains a string not an int
$i = [int] $o;
}# catch the error and display
catch {
"Error in conversion"
"Error record: {0}" -f $Error[0]
}
# Clean up
finally {
"`$i = {0}" -f $i
"`$i = {0}" -f $i.gettype()
}
# End of Script

gerry lowry
link is to c++ not c# ~~ docerr
http://msdn.microsoft.com/en-us/library/6dekhbbc.aspx
"The try, catch, and throw Statements" under Reference, above is a c++ page
Tags : docerr

timschwallie
Missing examples and scenarios
How does it work with return?
How does it work with nested try-catch?
How does it work with nested try-catch and using clauses?

In other words, when in the events of a method does try-catch actually run and in what order of precedence?

How about this for an example (please excuse the formatting cut and paste didn't quite work)? If you actually run this, note how the method doesn't exit until all the finally's have finished....something else to add to the write up here.

private

void button2_Click(object sender, EventArgs e)

{
Debug.WriteLine(DateTime.Now.Ticks.ToString() + "calling method 2 ");

long i = SomeMethod2();

Debug.WriteLine(DateTime.Now.Ticks.ToString() + "back from method 2");

Debug.WriteLine("");

}

privatelong SomeMethod2()

{

try

{
Debug.WriteLine(DateTime.Now.Ticks.ToString() + "inside method 2");

using (MemoryStream ms = newMemoryStream())

{

try

{
Debug.WriteLine(DateTime.Now.Ticks.ToString() + "inside first try 2");

Debug.WriteLine(DateTime.Now.Ticks.ToString() + "done first try 2");

}

finally

{
Debug.WriteLine(DateTime.Now.Ticks.ToString() + "inside finally for first try 2");

Thread.Sleep(1000);

Debug.WriteLine(DateTime.Now.Ticks.ToString() + "slept a second in finally for first try 2");

}

//second try

try

{
Debug.WriteLine(DateTime.Now.Ticks.ToString() + "inside second try 2");

Debug.WriteLine(DateTime.Now.Ticks.ToString() + "returning instance, done with try's 2");

}

finally

{
Debug.WriteLine(DateTime.Now.Ticks.ToString() + "inside finally second instance before return 2");

Thread.Sleep(1000);

Debug.WriteLine(DateTime.Now.Ticks.ToString() + "slept a second in finally second instance before return 2");

}

}
returnDateTime.Now.Ticks;

Debug.WriteLine(DateTime.Now.Ticks.ToString() + "after return, should not run. 2");

}

finally

{
Debug.WriteLine(DateTime.Now.Ticks.ToString() + "inside outer finally 2");

}

}

Tags :

Page view tracker