Home » C# Basics » 06 - Exception Handling
6

Understanding exceptions

Explains how exceptions are formed in programming

To understand what exceptions are and how they occur, let us make a simple console application.

Start the IDE and create a new console project. Inside the Main method, type the following code -

static void Main(string[] args) { int num1, num2, answer;
Console.WriteLine("Please enter the first number"); num1 = int.Parse(Console.ReadLine()); Console.WriteLine("Now enter the second number"); num2 = int.Parse(Console.ReadLine());
answer = num1 / num2;
Console.WriteLine("The result is {0}", answer);
}

The code is very simple. We have declared three variables. Two of them are used to store numbers entered by the user (num1 and num2). The third variable (answer) stores the result of the division. Finally, we display the result to the user.

Save the project and then press Ctrl+F5 from keyboard to run the application. Enter 10 and 2 as the input values:

As we can see, everything works just as expected.

Now enter 10 and 0 as the input values:

What happened here is an exception. Since the program does not know how to divide an integer by zero, it throws an exception and the program crashes. Although we can see what the exception is (System.DivideByZeroException : Attempted to divide by zero) in the output screen, for the user, this is not a good experience or a useful error message.

Run the program once again with 10 and "Two" as input values:

Here is another exception. The second input is a string while the program was expecting an integer. Hence, it throws the System.FormatException exception.

We can see that during the program execution, some unforeseen situations can cause the program to crash. Incorrect input, missing files or unavailable databases can result in exceptions.