C# Simplified, part 5: Error Handling and Files - Try-Catch clause
(Page 2 of 8 )
Before proceeding to learn the application of the try-catch clause, let’s consider a situation in which the exception is not handled properly. In listing 5.1, an attempt is made to divide a number by zero, which ultimately results in division by zero error.
Listing 5.1
using System;
class WithoutExcep
{
public static void Main()
{
int x = 5;
int y = 0;
int z = x/y;
Console.WriteLine(z);
}
}
If you execute the above program, the C# interpreter produces a dialog box.
If you click yes, a new instance of Visual Studio .NET debugger will open up, and upon selecting No you will get an output as shown below:
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
at WithoutExcep.Main()
In order to avoid this error, you must wrap the portion of the above code which causes trouble with a try clause, and it should be followed by a catch clause. The statements inside the catch block are executed only when an exception occurs. The main advantage to handling this exception is that users are provided with user-friendly error messages, rather than a set of unrecognized statements and dialog boxes. Listing 5.2 is a modified version of listing 5.1. The code properly handles the possible error with a try-catch block.
Listing 5.2
using System;
class WithExcep
{
public static void Main()
{
try
{
int x = 15;
int y = 0;
int z = x/y;
Console.WriteLine(z);
}
catch(Exception)
{
Console.WriteLine("Error occurred, unable to compute");
}
}
}
If you execute the above code, the statement inside the catch block will be printed. It will not produce an error message as you have seen above. Try to replace line 9 with the following code and observe the result:
int y = 5;
You can also retrieve system specific error messages with the help of an exception variable, along with your own error message. Listing 5.3 is a modified version of listing 5.2. The only difference is in the catch block, where I have applied a variable named e and called in the statement which encloses the catch block.
Listing 5.3
using System;
class WithExcep2
{
public static void Main()
{
try
{
int x = 15;
int y = 0;
int z = x/y;
Console.WriteLine(z);
}
catch(Exception e)
{
Console.WriteLine("Error occurred: \n" +e);
}
}
}
The resulting output of the above code is shown below:
Error occurred:
System.DivideByZeroException: Attempted to divide by zero.
at WithExcep2.Main()
Next: Finally clause >>
More C# Articles
More By Anand Narayanaswamy