Lost Password?


  #1 (permalink)  
Old 06-20-2008, 12:24 PM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,589
Last Blog:
Web slideshow in JavaS...
Rep Power: 76
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Wink Exception Handling in .NET

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:
csharp Code:
  1. try
  2. {
  3.  //Code goes here.
  4. }
  5. catch (Exception exc)
  6. {
  7.  //If an error occurs, this block of code runs. The variable exc contains information about the exception.
  8. }
  9. finally
  10. {
  11.  //This code will ALWAYS run, regardless of whether an exception occured.
  12. }
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!
__________________


Mr. Xav | Website | Forums | Blog

Last edited by Xav; 06-20-2008 at 12:27 PM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #2 (permalink)  
Old 06-20-2008, 12:35 PM
Jordan's Avatar   
Jordan Jordan is offline
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Posts: 9,224
Last Blog:
Ext JS or Ext GWT
Rep Power: 20
Jordan is just really niceJordan is just really niceJordan is just really niceJordan is just really nice
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan
Default Re: Exception Handling in .NET

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
__________________
CodeCall Blog | CodeCall Wiki | Shareware Site | Linux Forum | Write a Blog
The CodeCall Wiki is now fully integrated with vBulletin users! Check it out and add some new pages!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 06-20-2008, 12:36 PM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,589
Last Blog:
Web slideshow in JavaS...
Rep Power: 76
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Default Re: Exception Handling in .NET

As promised.
And now my rep bar has one light green bar!
__________________


Mr. Xav | Website | Forums | Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 06-21-2008, 10:29 AM
gaylo565's Avatar   
gaylo565 gaylo565 is offline
Programmer
 
Join Date: May 2007
Location: flagstaff, az
Posts: 187
Last Blog:
String Manipulation wi...
Rep Power: 9
gaylo565 is a jewel in the roughgaylo565 is a jewel in the roughgaylo565 is a jewel in the rough
Default Re: Exception Handling in .NET

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.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 06-21-2008, 03:11 PM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,589
Last Blog:
Web slideshow in JavaS...
Rep Power: 76
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Default Re: Exception Handling in .NET

Hey, thanks gaylo565!
__________________


Mr. Xav | Website | Forums | Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #6 (permalink)  
Old 06-24-2008, 11:06 PM
John's Avatar   
John John is offline
Co-Administrator
 
Join Date: Jul 2006
Age: 20
Posts: 3,433
Last Blog:
Google Web Toolkit
Rep Power: 20
John has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond reputeJohn has a reputation beyond repute
Send a message via AIM to John Send a message via MSN to John
Default Re: Exception Handling in .NET

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.
__________________
CodeCall Blog | CodeCall Wiki | Shareware | Linux Forum | My Blog
Chat with other CodeCall members on IRC; connect to irc.codecall.net and join #codecall
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 06-25-2008, 02:33 PM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,589
Last Blog:
Web slideshow in JavaS...
Rep Power: 76
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Default Re: Exception Handling in .NET

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


Mr. Xav | Website | Forums | Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Tags
compile, error, exception, handling, runtime



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
C# .NET Resources NeedHelp C# Programming 7 04-01-2008 11:05 AM
Microsoft .NET 3.0 Jordan General Programming 7 12-08-2006 10:18 AM
Visual Studio .NET Tips and Tricks free ebook Jordan Software Development Tools 2 09-14-2006 03:12 PM
What is .NET anyway? DevilsCharm C# Programming 4 07-31-2006 08:38 PM
.net Crane Software Development Tools 4 07-14-2006 10:50 AM


All times are GMT -5. The time now is 11:49 AM.

Contest Stats

WingedPanther ........ 2753.6
Xav ........ 2704
Brandon W ........ 1702.32
John ........ 1207.73
marwex89 ........ 1175.24
morefood2001 ........ 966.05
dcs ........ 655.75
Steve.L ........ 475.59
orjan ........ 418.58
Aereshaa ........ 383.54

Contest Rules

CodeCall Goal

Goal: 100,000 Posts
Complete: 97%

Ads