Introduction
Try catch in C# helps catch errors and exceptions in .NET apps The try block holds the suspected code that may get exceptions. When an exception is thrown, the .NET CLR checks the catch block and whether the exception is handled. One try block can have multiple catch blocks. A try-catch statement can have other nested try-catch statements.
Try catch in C#
In C#, the try catch statement is responsible for exception handling. The suspect code is placed inside the try block, and the catch declares an exception. A typical try..catch block looks like Listing 1.
try
{
// Suspect code
}
catch (Exception e)
{
// Action after the exception is caught
}
Listing 1
Let's look at the code in Listing 2, which divides an int with 0. First, we put the suspected code within the try block and catch the exception and generate a human-readable error message in the catch block.
try
{
int i = 20;
// Suspect code
int result = i / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Attempted divide by zero. {0}", ex.Message);
}
Listing 2
The code in Listing 2 will throw an exception. In this case, we already know the issue to catch the exception, but the core purpose of exception handling is when we don't know when the error might occur.
Now, let's say you've to use a class written by other developers that has a method, DivideNumer. See Listing 3.
static double DivideNumber(double num1, double num2)
{
if (num1 < num2)
num1 += 20;
return num1 / num2;
}
Listing 3
This is ideal to use a try..catch because we're unsure when an error may occur. See Listing 4
try
{
int i = 20; int j = 0;
double result = DivideNumber(i, j);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Attempted divide by zero. {0}", ex.Message);
}
Listing 4
Multiple catch blocks
C# allows using multiple catch in a try..catch block to catch specific exceptions. Let's take at the code in Listing 5, which may generate Stack overflow, divide by zero, and invalid cast exceptions. We can handle this using separate catch blocks for each exception type.
try
{
string mystring = default;
mystring.Insert(0, "hello");
int i = 20;
int j = 0;
double result = DivideNumber(i, j);
object obj = default;
int i2 = (int)obj;
// Suspect of casting error
}
catch (StackOverflowException ex) {
Console.WriteLine("Overflow. {0}", ex.Message);
}
catch (DivideByZeroException ex) {
Console.WriteLine("Attempted divide by zero. {0}", ex.Message);
}
catch (InvalidCastException ex) {
Console.WriteLine("Invalid casting. {0}", ex.Message);
}
Listing 5
Handle general exceptions
What if we don't know what kind of exception we will get? In that case, we use the Exception class to handle all exceptions. See Listing 6. The Exception block will handle any exceptions not caught by the previous catch blocks.
try
{
string mystring = default;
mystring.Insert(0, "hello");
int i = 20;
int j = 0;
double result = DivideNumber(i, j);
object obj = default;
int i2 = (int)obj;
// Suspect of casting error
}
catch (StackOverflowException ex) {
Console.WriteLine("Overflow. {0}", ex.Message);
}
catch (DivideByZeroException ex) {
Console.WriteLine("Attempted divide by zero. {0}", ex.Message);
}
catch (InvalidCastException ex) {
Console.WriteLine("Invalid casting. {0}", ex.Message);
}
catch (Exception ex) {
Console.WriteLine("General exception. {0}", ex.Message);
}
Listing 6
The try..finally
When an exception occurs in a try block, the program control goes to the catch block if the exception is handled; otherwise, the program execution stops. But often, we require some code to be executed even when an exception occurs. One of the key purposes of the "finally" block is to clean up any resources used in the try block. For example, if an IO resource is used to open and read a file, the IO resource must be released.

Join the conversation! Your thoughts help the community grow.