Csharp/CSharp Tutorial/Language Basics/Finally

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Dispose a StreamWriter in finally block

<source lang="csharp">using System; using System.IO; public sealed class MainClass {

   static void Main(){
       StreamWriter sw = new StreamWriter("Output.txt");
       try {
           sw.WriteLine( "This is a test of the emergency dispose mechanism" );
       }
       finally {
           if( sw != null ) {
               ((IDisposable)sw).Dispose();
           }
       }
   }

}</source>

finally block is always executed even if an exception was thrown in the try

<source lang="csharp">using System; using System.IO; class Processor {

   public void ProcessFile()
   {
       FileStream f = new FileStream("wrongNameFile.txt", FileMode.Open);
       try
       {
           StreamReader t = new StreamReader(f);
           string    line;
           while ((line = t.ReadLine()) != null)
           {
               Console.WriteLine(line);
           }
       }
       finally
       {
           f.Close();
       }
   }

} class Test {

   public static void Main()
   {
       Processor processor = new Processor();
       try
       {
           processor.ProcessFile();
       }
       catch (Exception e)
       {
           Console.WriteLine("Exception: {0}", e);
       }
   }

}</source>

Exception: System.IO.FileNotFoundException: Could not find file "C:\Java_Dev\WEB\dev\CSharp\wrongNam
eFile.txt".
File name: "C:\Java_Dev\WEB\dev\CSharp\wrongNameFile.txt"
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean
 useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, St
ring msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode)
   at Processor.ProcessFile()
   at Test.Main()

Using finally

Sometimes you can define a block of code that will execute when a try/catch block is left.

The general form of a try/catch that includes finally is shown here:


<source lang="csharp">try {

       // block of code to monitor for errors
   }
   catch (ExcepType1 exOb) {
       // handler for ExcepType1 
   }
   catch (ExcepType2 exOb) {
       // handler for ExcepType2 
   }
   .
   .
   .
   finally {
       // finally code
   }</source>