try-finally (C# Reference)
This page is specific to:.NET Framework Version:1.12.03.03.54.0
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.

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

Community Content

Wrong
Added by:Thomas Lee

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).
definition also horrible
Added by:Thomas Lee

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.

Try/Catch/Finally Sample, using PowerShell
Added by:Thomas Lee

<#
.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
link is to c++ not c# ~~ docerr
Added by:gerry lowry
http://msdn.microsoft.com/en-us/library/6dekhbbc.aspx
"The try, catch, and throw Statements" under Reference, above is a c++ page
© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View