O'Reilly logo

C# 3.0 Pocket Reference, 2nd Edition by Joseph Albahari, Ben Albahari

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

A try statement specifies a code block subject to error-handling or clean-up code. The try block must be followed by a catch block,a finally block, or both. The catch block executes when an error occurs in the try block. The finally block executes after execution leaves the try block (or if present, the catch block), to perform clean-up code, whether or not an error occurred.

A catch block has access to an Exception object, which contains information about the error. You use a catch block to either compensate for the error or rethrow the exception. You rethrow an exception if you merely want to log the problem, or if you want to rethrow a new, higher-level exception type.

A finally block adds determinism to your program by always executing no matter what. It’s useful for clean-up tasks such as closing network connections.

A try statement looks like this:

	try
	{
	  ... // exception may get thrown within execution of
	      // this block
	}
	catch (ExceptionA ex)
	{
	  ... // handle exception of type ExceptionA
	}
	catch (ExceptionB ex)
	{
	  ... // handle exception of type ExceptionB
	}
	finally
	{
	  ... // clean-up code
	}

Consider the following program:

	static void Main()
	{
	  int x = 3, y = 0;
	  Console.WriteLine (x / y);
	
	}

y is zero, so the runtime throws a DivideByZeroException, and our program terminates. We can prevent this by catching the exception as follows:

	static void Main( )
	{
	  try
	  {
	    int x = 3, y = 0;
	    Console.WriteLine (x / y);
	  }
	  catch (DivideByZeroException ex) { Console.WriteLine ...

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