C# Catch Examples

Catch keyword

In catch we handle exceptions. The try-catch pattern in the C# language provides an alternative flow control. It traps errors in an efficient and clear way. The catch block allows an optional variable. And multiple catch blocks can be stacked to provide more control.

Keywords

Example

Note

To begin, this example program shows three different patterns of using try-catch blocks. Please notice the different syntaxes used in the catch blocks. After the catch keyword, you can use parentheses to declare an exception variable. This variable can optionally be named. In the third example, you can have more than one catch block in a row; the most general catch comes last.

Program that uses catch blocks [C#]

using System;

class Program
{
    static void Main()
    {
	// You can use an empty catch block.
	try
	{
	    DivideByZero();
	}
	catch
	{
	    Console.WriteLine("0");
	}
	// You can specify a variable in the catch.
	try
	{
	    DivideByZero();
	}
	catch (Exception ex)
	{
	    Console.WriteLine("1");
	}
	// You can use multiple catch blocks.
	try
	{
	    DivideByZero();
	}
	catch (DivideByZeroException)
	{
	    Console.WriteLine("2");
	}
	catch
	{
	    Console.WriteLine("3");
	}
    }

    static int DivideByZero()
    {
	int value1 = 1;
	int value2 = int.Parse("0");
	return value1 / value2;
    }
}

Output

0
1
2
Warning

Exception. The program throws an exception three times; each call to the DivideByZero method causes an exception to be raised. It does this by dividing by zero. Three lines are written to screen; these numbers indicate what catch blocks were executed in the control flow.

DivideByZeroException

Summary

The C# programming language

Exception handling constructs provide a powerful way of error processing in the C# language; the catch block is a specific part of this construct. By going outside of the imperative, C-based control flow, you can more easily trap unexpected conditions. This can lead to clearer, more determined code that is more logically followed, provided you understand the principles of this alternative control flow.

Exception Handling
.NET