This tutorial aims to introduce you to the concept of exceptions in C#. An exception is an error that occurs during the execution of a program and disrupts its normal flow. By the end of this tutorial, you should have a clear understanding of what exceptions are, how to handle them, and the best practices for exception handling in C#.
Before you start, you should have a basic understanding of C# programming, including variables, data types, control structures, and functions/methods.
In C#, the primary method of handling exceptions is through the use of try-catch
blocks. When the code within a try
block throws an exception, the execution is transferred to the appropriate catch
block where the exception can be handled.
A try-catch
block is written as follows:
try
{
// Code that might throw an exception.
}
catch (ExceptionType ex)
{
// Code to handle the exception.
}
Where ExceptionType
is the type of exception you want to catch, and ex
is a variable to hold the exception object.
The finally
block is used to execute code, whether an exception is thrown or not. It is often used for cleanup activities, such as closing files or releasing resources.
try
{
// Code that might throw an exception.
}
catch (ExceptionType ex)
{
// Code to handle the exception.
}
finally
{
// Code to be executed regardless of whether an exception occurs or not.
}
Here's an example of a try-catch
block in action:
try
{
int[] numbers = new int[5];
numbers[6] = 9; // This code throws an IndexOutOfRangeException.
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
}
In this code, we're trying to assign a value to an index that doesn't exist in the array, which throws an IndexOutOfRangeException
. The catch
block catches this exception and prints the exception message to the console.
Here's an example that includes a finally
block:
StreamReader reader = null;
try
{
reader = new StreamReader("nonexistent_file.txt");
Console.WriteLine(reader.ReadToEnd());
}
catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (reader != null)
reader.Close();
}
In this example, we're trying to open and read a file that doesn't exist. This throws a FileNotFoundException
which is caught and handled. The finally
block ensures that the StreamReader
is closed, even if an exception is thrown.
In this tutorial, we've covered:
- What exceptions are and how they disrupt program flow.
- How to handle exceptions using try-catch
blocks.
- The use of finally
block for cleanup activities.
- Examples of exception handling in C#.
The next step is to learn about different types of exceptions that are built into the .NET framework and how to create and use custom exceptions. You can find more information in the Microsoft Documentation.
Write a program that catches a DivideByZeroException
. Try dividing a number by zero in a try
block and catch the exception in a catch
block. Print the exception message to the console.
Write a program that opens a file using a StreamReader
in a try
block. In a catch
block, catch the FileNotFoundException
and print the exception message to the console. Use a finally
block to close the StreamReader
.
Write a program that catches multiple types of exceptions. In the try
block, write code that could throw more than one type of exception. Have separate catch
blocks for each type of exception.
DivideByZeroException
csharp
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
This code attempts to divide a number by zero, which throws a DivideByZeroException
. The catch
block catches this exception and prints the exception message.
FileNotFoundException
csharp
StreamReader reader = null;
try
{
reader = new StreamReader("nonexistent_file.txt");
Console.WriteLine(reader.ReadToEnd());
}
catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (reader != null)
reader.Close();
}
This code is similar to the try-catch-finally
example above. It tries to open a nonexistent file, catches the resulting FileNotFoundException
, and ensures the StreamReader
is closed with a finally
block.
Multiple Exceptions
csharp
try
{
int[] numbers = new int[5];
numbers[6] = 9; // Throws IndexOutOfRangeException.
int result = 10 / 0; // Throws DivideByZeroException.
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
This code includes two lines that each throw a different type of exception. There are two catch
blocks, each designed to catch and handle a different type of exception.