C# try catch

Summary: in this tutorial, you’ll learn about exceptions and how to use the C# try...catch statement to handle exceptions.

Introduction to the C# try catch statement

Exceptions are runtime errors in a program, which violate system constraints. For example, when the program attempts to divide a number by zero, an exception occurs. When an exception occurs, the system catches it and raises the exception.

If the program doesn’t handle the exception properly, it will crash. For example, the following program will crash due to an exception:

int amount = 100;
int qty = 0;

int result = amount / qty;

Console.WriteLine(result);Code language: C# (cs)

In this example, the program crashed with the following error message:

System.DivideByZeroException: 'Attempted to divide by zero.'Code language: C# (cs)

In this error message, the exception name is System.DivideByZeroException. And the error message indicates that the program attempted to divide by zero.

If you don’t handle exceptions, users will see unfriendly error messages. To goal of exception handling is to respond to an exception with one of the following actions:

  • Display a user-friendly message to users and request users to take corrective actions to keep the program running properly.
  • Log the information of the exception to a file so that you can address it later.
  • Clean up any external resources such as database connections.

To handle exceptions, you use the try...catch statement:

try
{
    // statements to be guarded for exceptions
}
catch
{
    // exception handler

}Code language: C# (cs)

In this syntax:

  • First, place the statements that you want to guard for exceptions in the try block.
  • Second, provide the exception handler in the catch block to handle the exception.

When an exception occurs in the try block, the control of the program immediately jumps to the catch block.

The following program shows how to use the try...catch statement to handle the exception:

int amount = 100;
int qty = 0;

try
{
    int result = amount / qty;
    Console.WriteLine(result);
}
catch
{
    Console.WriteLine("The program was terminated due to an error.");
}

Console.WriteLine("Bye!");Code language: C# (cs)

Output:

The program was terminated due to an error.
Bye!Code language: C# (cs)

In this program, the DivideByZeroException exception occurred that caused the catch block to be executed and showed the error message. The program ran without crashing.

If you know the exact type of exception, you can specify it in the catch block. For example:

int amount = 100;
int qty = 0;

try
{
    int result = amount / qty;
    Console.WriteLine(result);
}
catch(DivideByZeroException e)
{
    Console.WriteLine("The program was terminated due to an error.");
    Console.WriteLine($"Message: {e.Message}");
    Console.WriteLine($"Source: {e.Source}");
    Console.WriteLine($"Stack: {e.StackTrace}");
}

Console.WriteLine("Bye!");Code language: C# (cs)

Output:

The program was terminated due to an error.
Message: Attempted to divide by zero.
Source: Program
Stack:    at Program.<Main>$(String[] args) in D:\csharp\Program.cs:line 6
Bye!Code language: C# (cs)

In this example, the catch block caught the DivideByZeroException exception and assigned an instance to the e variable. The DivideByZeroException object (e) has detailed information about the exception such as:

  • Message – contains the error message that explains the cause of the exception.
  • Source – contains the name of the assembly where the exception originated.
  • StackTrace – describes where the exception occurred.

Exception types

C# defines many exception classes, each representing a specific type. All exception classes are derived from the System.Exception class, which in turn is derived from the System.Object class.

The following picture illustrates the exception hierarchy:

More on the catch clause

The catch clause handles exceptions. It has four forms.

1) General catch clause

The general catch clause does not have a parameter list of the catch keyword. It matches any exception raised in the try block:

try
{ 
}
catch
{
}Code language: C# (cs)

2) Specific catch clause

A specific catch clause specifies the name of an exception class as a single parameter. It matches any exception with the name that matches the parameter:

try
{
    // statement
}
catch (ExceptionType)
{
    // handle exception with the ExceptionType
}Code language: C# (cs)

3) Specific catch clause with object

The specific catch clause with an object includes an exception variable after the name of the exception class. This exception variable references the exception object. By using an exception variable, you can access specific information about the exception.

try
{
    // statement
}
catch (ExceptionType e)
{
    // handle exception with the ExceptionType
}Code language: C# (cs)

4) Specific catch with a predicate

The specific catch is like a specific catch with an object but also includes a predicate. The catch will execute only if the condition in the predicate is true:

try
{
    // statement
}
catch (ExceptionType e) where (predicate)
{
    // handle exception with the ExceptionType
}Code language: C# (cs)

Summary

  • Exceptions are runtime errors that occurred in the program.
  • Use the try...catch statement to handle exceptions.
Was this tutorial helpful ?