C# Managing Errors

In every computer program released there are always problems (known as "bugs"), and these problems can occur at any time. This can be easily solved by using a try catch block to "catch" the exception. There are different types of exceptions which can occur, such as an overflowException or a formatException. Create a new C# Console Application and name it ManagingErrors.

Example

 string x = null;

            int a = 10;
            Console.WriteLine("Pick a number");
            x = Console.ReadLine();
            Console.WriteLine(int.Parse(x) + a);
            Console.ReadLine();

This is a simple program which has been used in previous tutorials: we made a string variable and an integer variable, we got the user input and the added together x and a. Now run the program, type in a number, such as 20, and you will get the answer 30. This works perfectly, but what happens if you  type the letter K ? Well you will get an exception saying "Input string was not in correct format" Try starting the program again and typing in K. You will see this message:

C# Managing Errors - Format Exception

We can use a try catch block to "catch" exceptions.

Syntax

   try
            {

            }

            catch (Exception)

            {
                throw;
            }

The catch block is required; it specifies the type of exception you want to catch. To put that code in a try catch block, copy the following:

   try
            {
                Console.WriteLine("Pick a number");
                x = Console.ReadLine();
                Console.WriteLine(int.Parse(x) + a);
            }

            catch (FormatException fex)
            {
               Console.WriteLine(fex.Message);
            }
            Console.ReadLine();

When you run this type in 'K', you will get a message saying "Input string was not in correct format", however the program won't crash.  Here we caught the "FormatException". There are different kinds of exceptions: if you type 'exception' you will see intellisense come up with a many different types of exceptions. We will not outline all of them, but two common examples are given here. Another type of exception is overflow exception, which happens when arithmetic results  overflow (go out of range). The range for int is -2,147,483,648 to 2,147,483,647 which is a pretty big number. Run the program again, and this time for your number type in 2147483647893. You will get an overflow exception and the program will close. Here the catch handler did not catch the exception because it was not a format exception.

Nested Catch Handlers

We can have nested catch handlers to catch various types of exceptions. After the last catch handler code block } add:

 catch (OverflowException oEx) {
                Console.WriteLine(oEx.Message);
            }

This time type 2147483647893 as your number and the program won't crash, but you will get a message in the console window saying "Value was either too large or too small for Int32". There are many more errors which can come up, so how can we catch any error that could occur? In this case we use the keyword 'Exception':

 catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

This will catch any exception which occurs. If you have a nested catch handler this should always be at the end; otherwise it will simply catch all the exceptions.

Summary

There are many Exceptions in C#; this tutorial covered some basic examples to outline managing errors, which will ensure your programs are robust. Of course this means you should not use try catch blocks everywhere, but put them where necessary. For example, if you have a piece of code which sends email, many errors can occur: the email is not in the correct format, the password is not correct, the server requires SSL, etc.

Handling Errors Video Tutorial

Webucator, a technology training company, has produced an excellent video tutorial inspired by our C# Managing Errors tutorial for their C# classes. You can watch it here: