Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
C# Reference
C# Keywords
 try-finally

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
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.

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.

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

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Wrong      Andrei.Gavrila ... Thomas Lee   |   Edit   |   Show History

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      Dan Marinescu ... Thomas Lee   |   Edit   |   Show History

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 What's this?: Add a tag
Flag as ContentBug
Try/Catch/Finally Sample, using PowerShell      Thomas Lee   |   Edit   |   Show History

<#
.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
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker