try and catch Statements
You can handle errors by using a try…catch statement. You wrap the code that you suspect to trigger an error inside a try block. The catch block contains the codes to be executed when an error is encountered. The following program demonstrates using try…catchstatements.
using System;
namespace TryCatchDemo
{
public class Program
{
public static void Main()
{
int result;
int x = 5;
int y = 0;
try
{
result = x / y; // Exception will be thrown
}
catch
{
Console.WriteLine("An attempt to divide by 0 was detected.");
}
}
}
}
Example 1 – The try…catch Statements
An attempt to divide by 0 was detected.
Inside the try block, we divided x which has a value of 5 by y which contains 0. The calculation will cause a DivideByZeroException. Note in C#, saying an exception was thrown simply means that a particular error was encountered by the program. That’s why the catchblock was named like that because it “catches” the exceptions that were thrown. Since an exception was thrown, the codes inside the catch block will be executed. If the line of code causes an error, it will jump immediately to the catch block skipping the following lines. Therefore:
try
{
result = x / y; //Error: Jump to catch block
Console.WriteLine("This line will not be executed.");
}
catch
{
Console.WriteLine("An attempt to divide by 0 was detected.");
}
You can indicate a specific type of exception that you want to handle by indicating it on the catch block like this:
try
{
result = x / y; //ERROR
}
catch (DivideByZeroException)
{
Console.WriteLine("An attempt to divide by 0 was detected.");
}
Additionally you can provide a variable that will hold the values for the exception.
try
{
result = x / y; //ERROR
}
catch (DivideByZeroException error)
{
Console.WriteLine(error.Message);
}
Attempted to divide by zero.
The variable will hold useful informations about the exception that was thrown. We used the Message property to show the description of the message. Every exception class has descriptions about the errors. You will learn more properties of Exception in later lessons.
If you are expecting more than one error to occur within the try block, you can provide multiple catch blocks but you should specify the type of exception for each of them.
int result;
int x = 5;
int y;
try
{
y = Int32.Parse(Console.ReadLine());
result = x / y;
}
catch (DivideByZeroException error)
{
Console.WriteLine(error.Message);
}
catch (FormatException error)
{
Console.WriteLine(error.Message);
}
Since the value of y is determined from the input of the user, the value can be a non-zero integer. But there is a problem. What if the user types a non-numerical value such as a letter. They cannot be properly converted to an int datatype so a FormatException will be thrown. When this exception is thrown, the catch block for the FormatException will be executed. The calculation for the quotient of the x and y will be skipped.
What if you want to catch all the possible errors inside the try block? Simply use the generic Exception class. Every exception in .NET inherits from this class therefore, you can store any type of exception inside an object of the Exception class.
try
{
//Put your codes to test here
}
catch (Exception error)
{
Console.WriteLine(error.Message);
}
Now, you don’t need to worry that an error may get away. The catch block will handle every error that is detected within the try block and then show the appropriate message for that particular exception.
Note that if you will use the Exception base class in a catch block together with other derived Exception classes, then the base Exception class must be placed at the final catch block.
try
{
//Put your codes to test here
}
catch (DivideByZeroException)
{
Console.WriteLine("Division by zero is not allowed.");
}
catch (FormatException)
{
Console.WriteLine("Error on converting the data to proper type.");
}
catch (Exception)
{
Console.WriteLine("An error occured.");
}
This makes sense because if you place it in the first catch block, then it will always be match first and the other catch blocks after it will never be executed even if they have the specific exception that matches the one thrown by the program.
You can also use the is operator or check the type of the exception to assign specific behaviors depending on the errors caught.
try
{
}
catch(Exception error)
{
if (error is DivideByZeroException)
{
Console.WriteLine("Cannot divide by zero!");
}
if (error is FormatException)
{
Console.WriteLine("Format cannot be accepted!");
}
}
The catch block uses the Exception class to catch all the exceptions thrown by the program. Inside the catch block, you can then test what kind of Exception was thrown using an if statement and the is keyword.