C#:.NET:Exception

.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda Parse Path Process Property Regex Replace Row Sort Split Static StringBuilder Substring Switch Tuple Window

Catch, when. In catch we handle exceptions. An alternative flow, the try-catch pattern traps errors, separating them in a clear way. Programs become easier to read.TryFinally
Catch features. The catch block allows an optional variable. Multiple catch blocks can be stacked to provide more control. And "when" can filter exceptions.
An example. This program shows three patterns of using try-catch blocks. Please notice the syntaxes used in the catch blocks. We catch exceptions in different ways.

Variable: After the catch keyword, we use parentheses to declare an exception variable. This variable can optionally be named.

Note: In the third example, we have more than one catch block in a row. The most general catch comes last.

Based on: .NET 4.6

C# program that uses catch blocks

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
Program notes. The program throws an exception three times. Calls to DivideByZero cause exceptions to be raised. We use int.Parse to prevent the compiler from spotting the error.DivideByZeroExceptionParseCompile-Time Error

Then: Three lines are written to screen. These numbers indicate what catch blocks were executed in the control flow.

Console.WriteLine
Filter, when. With the when-keyword, we filter exceptions. A condition (like one found in an if-statement) is the argument to when. This reduces complex logic in exception catch blocks.

Tip: We can stack "when" catch clauses. In this program we catch the ArgumentException in multiple ways.

C# program that uses catch, when, filters exceptions

using System;

class Program
{
    static void Main()
    {
	try
	{
	    throw new ArgumentException("Invalid x argument");
	}
	catch (ArgumentException ex) when (ex.Message == "Invalid x argument")
	{
	    // This is reached.
	    Console.WriteLine("X");
	}
	catch (ArgumentException ex) when (ex.Message == "Invalid y argument")
	{
	    // This is not reached.
	    // ... Change the string to have "y" and it will be reached.
	    Console.WriteLine("Y");
	}
    }
}

Output

X
In complex programs, exception handling is helpful. Catch is a key part of exception handling. By going outside of the control flow, we more easily trap unexpected conditions.