nedcomp hosting homepage

Producten en Diensten
Dedicated servers
Datacenter informatie
Partners, resellers
Helpdesk informatie
Technische docs, tools
Support homepage
ASP componenten
Praktische ASP, ASP.NET
Visual route server
Whois (domein gegevens)
Software documentatie
Whitepapers
Zoeken
Nedcomp / algemeen

Zoeken
 

Copyright © Nedcomp Hosting
Telefoon nr :   +31 184 670111
Fax nummer :   +31 184 631384
E-mailadres :   info@nedcomp.nl
 

C# Programmer's Reference  

try-finally

The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits. This statement takes the following form:

try try-block finally finally-block

where:

try-block
Contains the code segment expected to raise the exception.
finally-block
Contains the exception handler and the cleanup code.

Remarks

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.

// try-finally
using System;
public class TestTryFinally 
{
   public 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);
      }         
   }
}

Output

The following exception occurs:

System.InvalidCastException

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.

See Also

C# Keywords | <_pluslang_the_try.2c_.catch.2c_.and_throw_statements>Compare to C++ | Exception Handling Statements | throw | try-catch | Throwing Exceptions | C. Grammar