The goal of this tutorial is to empower you with the knowledge of using try-catch blocks in C# for effective exception handling in your applications.
By the end of this tutorial, you will be able to:
- Understand what try-catch blocks are and their purpose.
- Use try-catch blocks to handle exceptions in your C# programs.
- Implement best practices when working with try-catch blocks.
In C#, when an exceptional circumstance arises within a block of code, an exception is thrown. A try-catch block is used to capture these exceptions and handle them in a controlled manner, allowing your application to continue running.
The 'try' block contains the code that could potentially throw an exception, while the 'catch' block is used to handle any exceptions that are thrown in the 'try' block.
try
{
// Code that may cause an exception.
int x = 0;
int y = 5 / x;
}
catch (Exception ex)
{
// Code to handle the exception.
Console.WriteLine("An error occurred: " + ex.Message);
}
In this example, dividing by zero will throw a DivideByZeroException. The catch block captures this exception and writes the error message to the console.
try
{
// Code that may cause an exception.
string s = null;
string t = s.ToString();
}
catch (NullReferenceException ex)
{
// Handle more specific exceptions first.
Console.WriteLine("Caught a NullReferenceException: " + ex.Message);
}
catch (Exception ex)
{
// Handle more general exceptions last.
Console.WriteLine("An error occurred: " + ex.Message);
}
In this example, calling ToString on a null string will throw a NullReferenceException. The first catch block handles this specific exception type, while the second catch block handles all other exceptions.
In this tutorial, you've learned how to use try-catch blocks in C# to handle exceptions. You've also covered best practices and seen how to handle specific and general exceptions.
For further learning, consider exploring the 'finally' block, which can be used alongside 'try' and 'catch' to ensure a block of code runs whether an exception is thrown or not.
Write a program that attempts to parse an invalid number using int.Parse and catches the resulting exception.
Modify the previous program to catch a FormatException specifically, as well as a general Exception.
// Solution for Exercise 1
try
{
int number = int.Parse("invalid number");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
// Solution for Exercise 2
try
{
int number = int.Parse("invalid number");
}
catch (FormatException ex)
{
Console.WriteLine("Caught a FormatException: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
In these solutions, int.Parse is used to try to parse a string that is not a valid integer. This throws a FormatException, which is caught and handled.