Visual C# Guide
Exception Handling

The Exception class provides a code-based way of representing the information that arises when an error occurs during execution. If the exception is not handled (there is no code to be executed when it occurs), the program will crash. Handling exceptions can allow the program to continue when such an error occurs.

Catching An Exception

The following program catches the exception when it occurs. The parameter e can be used to find out more about the exact exception that occurs. The code within the try statement is the code which we believe may cause the exception.

Console.Write("Enter an integer: ");
string name = Console.ReadLine();
   int numEntered = System.Convert.ToInt32(name);
catch (Exception e)
   Console.WriteLine("Exception caught {0}", e.Message );

You can write more than one catch clause in this structure. This can be used to catch different types of exception and deal with them accordingly. Changing the parameter of the catch statement to say, ArithmeticException or DivideByZeroException would allow you to write code for different scenarios that may occur within the same program.

Having A Go

  1. Write a program that asks the user to input two integers. Divide the two integers and catch the exception that occurs if the second number is zero as well as ensuring that integers are entered.