Exception Handling in C# with .NET
Hello, Xav here. In this tutorial we will learn about the different errors in C#, and what you can do about them. Note that everything discussed here applies to all the .NET languages, including VB.NET, C# and managed C++. However, the exception handling syntax is different.
Nobody likes making mistakes. It's rarely a pleasant experience when your application freezes and an angry yellow window pops up telling you an error has occured. But in fact the .NET Framework, with the Visual Studio Express Editions, can make like a lot easier for you. Here's the lowdown:
There are two different types of errors:
A compile error occurs when the IDE (in this case Visual Studio) detects an error with the code. Usually the IDE automatically prevents the code from being run for a compile error. Examples of this are:
1. Forgetting a semicolon.
2. Forgetting to close a bracket.
3. Mispelling a variable name (although not with Option Strict turned off).
4. Trying to put a string value such as "Xav" into an integer variable.
These sorts of errors are fine, because the compiler clearly shows and highlights the errors, with wavy lines etc. You can easily see the problem because it describes the error, allowing you to easily correct the mistake. For example, if the errors says "Expected )" then you've obviously forgotten a bracket somewhere. "Cannot convert value of type String to type Int32" means you've messed up your data types. Whatever it is, they're far less problematic than the other type of error...
A runtime error, or exception, occurs whilst the program is running. They are devilishly hard to spot whilst writing the code, and even the IDE can't spot them. Examples of these are:
1. Trying to read a file that does not exist.
2. The program asks the user for their age. It then divides it by two. However, the user types "Xav" for their age.
You see the problem? In most cases these programs would work perfectly. However, sometimes, just sometimes, there are rare occasions where the conditions are just right (or just wrong) for an exception to occur. You cannot tell, for instance, what a user is going to type. You cannot tell whether a file will exist or not. You can not tell whether your Picture Viewer program is going to try and open a text file that the user selected or not. Therefore, we must account for these exceptions in our code.
There are actually many different types of exception, depending on the nature of the error. For example, a DivideByZeroException occurs when the program attempts to divide a number by zero. An InvalidCastException occurs when the program fails to convert a value from one data type to another. An OutOfMemoryException usually occurs when the program tries to open a file that is not the correct type.
When an error occurs in a program in VS, the program initially freezes. Then, the IDE window displays a message on the current line describing the nature of the error. Look at the message, and try to work out what sort of error it i, and why it is occurring.
When your program has been compiled and installed on the user's computers, they won't get that message. Instead, they'll get a confusing error message. Therefore, you need to account for the errors in your code.
You use a Try block, like so:
//Code goes here.
catch (Exception exc)
//If an error occurs, this block of code runs. The variable exc contains information about the exception.
//This code will ALWAYS run, regardless of whether an exception occured.
In programming terms, we say an exception is thrown. Note that the Finally section can be omitted, if not in use.
The code that could potentially throw an exception is placed in the try section. If an error occurs, the code execution leaves the try block on the line the error occured, and jumps to the catch section. You can pass the exception data to a parameter (I used "exc" here), and you could retrieve the message of the exception be using exc.Message. For example, you could display a message box to the user that told them of the error.
You can have multiple catch blocks with different exceptions, so you know exactly what error it was, and what to do about it. Note, though, that multiple circumstances can throw the same exception. Also, note that any exception is caught using the generic Exception class.
Exception handling needn't be scary. It makes your application more robust and secure, and should be tested vigorously to ensure every error possible can be caught and dealt with appropriately. By using the try block, the IDE does not freeze the program and break into debugging mode, allowing your program to continue running if something goes wrong.
Test yourself: Write a program that loads an image into a PictureBox, based on the user's selection from an OpenFileDialog. If the user selects a file that is not a picture, display a neat message box instead of generating an exception. Hint: Use the Image.FromFile() method to load the image, and catch the OutOfMemoryException.
If my tutorial was useful, please +rep. Leave any comments/suggestions/praise here!
Edited by Xav, 20 June 2008 - 08:27 AM.