try catch block example in c sharp

try Statements and Exceptions A try statement specifies a code block subject to error-handling or cleanup 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 cleanup code, whether or not an error occurred. A catch block has access to an Exception object that contains information about the error.

We 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: the CLR endeavors to always execute it. It’s useful for cleanup 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 { … // cleanup code }

Consider the following program:

class Test { static int Calc (int x) { return 10 / x; } static void Main()

{ int y = Calc (0); Console.WriteLine (y); } }

Because x is zero,

the runtime throws a DivideByZeroException,

and our program terminates.

We can prevent this by catching the exception as follows:

class Test { static int Calc (int x) { return 10 / x; } static void Main()

{ try { int y = Calc (0); Console.WriteLine (y); }

catch (DivideByZeroException ex)

{ Console.WriteLine (“x cannot be zero”); }

Console.WriteLine (“program completed”);

} }

OUTPUT: x cannot be zero program completed

The catch Clause A catch clause specifies what type of exception to catch.

This must either be System.Exception or a subclass of System.Exception. Catching System.Exception catches all possible errors. This is useful when: •

program can potentially recover regardless of the specific exception type. •

plan to rethrow the exception (perhaps after logging it). • Your error handler is the last resort, prior to termination of the program.