O'Reilly logo

C# Essentials by Peter Drayton, Ben Albahari, Brad Merrill

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

try Statements and Exceptions

try statement-block
[catch (exception type value ?)? statement-block ]+ |
finally statement-block |
[catch (exception type value ?)? statement-block ]+
finally statement-block

try Statement

The purpose of a try statement is to simplify dealing with program execution in exceptional circumstances. A try statement does two things. First, it lets exceptions thrown during the try block’s execution be caught by the catch block. Second, it ensures that execution can’t leave the try block without first executing the finally block. A try block must be followed by one or more catch blocks, a finally block, or both.

Exceptions

C# exceptions are objects that contain information representing the occurrence of an exceptional program state. When an exceptional state has occurred (e.g., a method receives an illegal value), an exception object may be thrown, and the call-stack is unwound until the exception is caught by an exception handling block. Here’s an example:

public class File {
  ...
  public static StreamWriter CreateText(string s) {
    ...
    if (!Valid(s))      
      throw new IOException("Couldn't create...", ...);
      ...
  }
}
class Test {
  ...
  void Foo(object x) {
    StreamWriter sw = null;
    try {
      sw = File.CreateText("foo.txt");
      sw.Write(x.ToString( ));
    }
    catch(IOException ex) {
      Console.WriteLine(ex);
    }
    finally {
      if(sw != null)
        sw.Close( );
    }
  }
}

catch

A catch clause specifies what exception type (including derived types) to catch. An exception must be of type System.Exception ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required