Information Technology Reference
In-Depth Information
Examples Using Specific catch Clauses
In the following code, the
catch
clause of a previous example has been modified to specifically
handle exceptions of the
DivideByZeroException
class. While in the other example, the
catch
clause would handle any exception raised in the
try
block, the current example will only han-
dle those of the
DivideByZeroException
class.
int x = 10;
try
{
int y = 0;
x /= y; // Raises an exception
}
Exception type
↓
catch ( DivideByZeroException )
{
...
Console.WriteLine("Handling an exception.");
}
For example, you could further modify the
catch
clause to use an exception variable. This
allows you to access the exception object inside the
catch
block.
int x = 10;
try
{
int y = 0;
x /= y; // Raises an exception
}
Exception type
Exception variable
↓
↓
catch ( DivideByZeroException e )
{
Accessing the exception variable
↓
Console.WriteLine("Message: {0}", e.Message );
Console.WriteLine("Source: {0}", e.Source );
Console.WriteLine("Stack: {0}", e.StackTrace );
}
This produces the following output:
Message: Attempted to divide by zero.
Source: Exceptions 1
Stack: at Exceptions_1.Program.Main() in C:\Progs\Exceptions 1\Exceptions 1\
Program.cs:line 14