Visual Basic Managing Errors

There are always problems with every program that is released (known as “bugs”), and they can occur at any time. We can solve these problems easily 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 VB Console Application and name it ManagingErrors. Copy the following:

Dim x As String = Nothing
Dim a As Integer = 10

        Console.WriteLine("Pick a number")
        x = Console.ReadLine()
        Console.WriteLine(Convert.ToInt32(x) + a)
        Console.ReadLine()

This is a simple program that we have seen in other tutorials. We have two variables, one a string and another an integer, we tell the user to pick a number and then add both values together, and we use Convert.ToInt32 to convert the string data to integer. Run the program, type in 20 and you will get the answer, 30. This works without any problems, but what happens if you type in the letter K? The program will crash and you will get an error saying “Input string was not in a correct format“,which looks like this:

Visual Basic Format Exception

This is a Format Exception; now we can put in the code to prevent the crashing: Try Catch block.

Syntax

 Try

        Catch ex As Exception

        End Try

Example

   Try

            Console.WriteLine("Pick a number")

            x = Console.ReadLine()

            Console.WriteLine(Convert.ToInt32(x) + a)

        Catch fEx As FormatException

            Console.WriteLine(fEx.Message)

        End Try


        Console.ReadLine()

fEx is a local variable, and the code executes as normal; however if the user types in a letter or non-integer then the Format Exception error message will appear. The code has simply been moved to the Try Catch block. If you try running it, the error message will appear in the console window and the program won’t crash. However, there are many exceptions which can happen. Another type of exception is Overflow Exception where the number goes out of range; for example an integer has a range between -2,147,483,648 to 2,147,483,648 which is a large number, however if the program goes over this, the catch handler will not catch it. Run the program again and this time enter 214748364833 for your number. The program will crash with the error “Value was either too large or too small for an Int32“. Stop the program and return to the IDE.

Nested Catch Handlers

We can have nested catch handlers for different types of exceptions. Put this code just below that Console.WriteLine(fEx.Message):

  Catch oEx As OverflowException

            Console.WriteLine(oEx.Message)

Now when you run the program and type 214748364833 the message will appear in the console window instead of crashing the program. There are many more exceptions which can occur, and we cannot go through all of them; the examples showed two common ones. So how would you catch any exception? In this case you just use the keyword ‘exception’. Let’s modify this code slightly:

Console.WriteLine(Convert.ToInt32(x) + a)

Change it so it looks like this:

Console.WriteLine(x + a)

Run the program and type a number (from 1 to 10), and the program should calculate as usual. Now type in a letter and watch how the program will crash with the message “Conversion from string “f” to type ‘Double’ is not valid” (f is the letter we chose for this test). None of the catch handlers handled the exception because the exception was a “InvalidCastException”. There are many more exceptions now to catch this exception. Below the overflowException, add another catch handler:

Catch ex As Exception

            Console.WriteLine(ex.Message)

This will catch all exceptions.

Summary

This tutorial covered how to manage errors, which will ensure your programs are robust. However, this does not mean you should write try catch statements everywhere in your code; only do so where problems are likely to go wrong. For example, if you have an email program many things can go wrong with sending email if it is not in the correct format, the password is not correct, the server is down, and so on.