CSharp - try Statements and Exceptions

What is try statement

A try statement marks a code block for error-handling or resource cleanup.

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 try block or catch block, to perform cleanup code, regardless if an error occurred.

The exception happened in try block is represented by an exception object.

A catch block has access to that Exception object that contains information about the error.

You use a catch block to either handle the error or rethrow the exception.

You rethrow an exception if you only want to log the exception, or to rethrow a new exception type.

A finally block is useful for cleanup tasks such as closing network connections.

Syntax

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
}

Example

Consider the following program:

class Test
{
     static int Calc (int x) => 10 / x;

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

Because x is zero, the runtime throws a DivideByZeroException.

We can prevent this by catching the exception as follows:

class Test
{
     static int Calc (int x) => 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");
     }
}

Related Topics

Quiz