Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Exception Handling in .NET

form

  • Please log in to reply
10 replies to this topic

#1 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 20 June 2008 - 08:24 AM

Exception Handling in C# with .NET

By Xav


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:

Errors
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.

Exceptions
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.

Handling Exceptions
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:

try
{
//Code goes here.
}
catch (Exception exc)
{
//If an error occurs, this block of code runs. The variable exc contains information about the exception.
}
finally
{
//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.

Conclusion
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.

Xav

If my tutorial was useful, please +rep. Leave any comments/suggestions/praise here!

Edited by Xav, 20 June 2008 - 08:27 AM.

  • 1
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#2 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 20 June 2008 - 08:35 AM

Excellent tutorial Xav! +rep - very nice read!

For those of you interested you can learn more about the types of exceptions here: Exception Members

And you can throw your own exceptions: Handling and Throwing Exceptions
  • 0

#3 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 20 June 2008 - 08:36 AM

As promised. :)
And now my rep bar has one light green bar!
  • 1
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#4 gaylo565

gaylo565

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 258 posts

Posted 21 June 2008 - 06:29 AM

Another nice tutorial xav:) I gave you a +rep for this one because of the consistent help you always try to give for my c# questions, and the effort you put into writing all these tutorials. Keep up the good work.
  • 0

#5 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 21 June 2008 - 11:11 AM

Hey, thanks gaylo565! ;)
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#6 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 24 June 2008 - 07:06 PM

After contemplating the idea of exceptions for several days, I've concluded (at least for my own software development purposes) it is a bad idea to depend on exceptions. I feel it is important to note, exceptions should not take the place of bounds checking (DivideByZeroException) and data validation (InvalidCaseException). In programming, its generally a good idea to think in the abstract, but an exception should be though of literally: "an exception to all rules" - something the programmer cannot guard against such as an OutOfMemoryException. None-the-less, I enjoyed the read.
  • 0

#7 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 25 June 2008 - 10:33 AM

I agree that exceptions should not be relied on instead of data validation, as a sort of escape route. The problem with exceptions is that you can't tell exactly why the error was caused - for example, by explicitly checking the bounds of a variable, you can tell the user exactly what went wrong. With an exception, however, you can only show the error message, as the specific exception could have been thrown by any of the statements.

That said, exceptions are a super way to keep out of trouble, and should be used on all potentially problematic statements. I.E. everywhere. ;)
  • 1
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#8 Egz0N

Egz0N

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1155 posts

Posted 16 January 2009 - 11:40 AM

haven't seen this one .. +rep from me Xav .. :)
  • 0

#9 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 16 January 2009 - 11:42 AM

Cheers, EgZ0N!
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#10 MathX

MathX

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1038 posts
  • Programming Language:Java

Posted 19 January 2009 - 06:36 AM

Nice!!! +rock
  • 0

Interested in participating in community events?
Want to harness your programming skill and turn it into absolute prowess?
Come join our programming events!


#11 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 20 January 2009 - 04:53 AM

lol - cheers.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download