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 ...

Get C# Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.