C#
  Home arrow C# arrow Page 2 - C# Exceptions
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

C# Exceptions
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2008-10-09

    Table of Contents:
  • C# Exceptions
  • The finally Block
  • Throwing Exceptions
  • Key Properties of System.Exception

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    C# Exceptions - The finally Block


    (Page 2 of 4 )

    A finally block always executes—whether or not an exception is thrown and whether or not the try block runs to completion. finallyblocks are typically used for cleanup code.

    Afinally block executes either:

    • After acatchblock finishes
    • After control leaves thetryblock because of ajumpstatement (e.g.,returnorgoto)
    • After thetryblock ends

    Afinallyblock helps add determinism to a program. In the following example, the file that we open always gets closed, regardless of whether:

    1. Thetryblock finishes normally.
    2. Execution returns early because the file is empty (EndOfStream).
    3. AnIOExceptionis thrown while reading the file.

        using System;
        using System.IO;

        class Test
        {
          static void Main ()
          {
            StreamReader reader = null;
            try
            {
              reader = File.OpenText ("file.txt");
              if (reader.EndOfStream) return;
              Console.WriteLine (reader.ReadToEnd ( ));
            }
            finally
            {
              if (reader != null) reader.Dispose ();
            }
          }
        }

    In this example, we closed the file by callingDisposeon theStreamReader. CallingDisposeon an object, within afinallyblock, is a standard convention throughout the .NET Framework and is supported explicitly in C# through theusingstatement.

    The using statement

    Many classes encapsulate unmanaged resources, such as file handles, graphics handles, or database connections. These classes implement System.IDisposable, which defines a single parameterless method named Dispose to clean up these resources. The usingstatement provides an elegant syntax for instantiating anIDisposableobject and then calling itsDisposemethod within afinallyblock.

    The following:

      using (StreamReader reader = File.OpenText ("file.txt"))
      {
        ...
      }

    is precisely equivalent to:

      StreamReader reader = File.OpenText ("file.txt");
      try
      {
        ...
      }
      finally
      {
        if (reader != null)
         ((IDisposable)reader).Dispose();
      }

    We cover the disposal pattern in more detail in Chapter 12 .

    More C# Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "C# 3.0 in a Nutshell, Third Edition, A...
     

    Buy this book now. This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.

    C# ARTICLES

    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    Stay green...Green IT