+ Reply to Thread
Page 1 of 2 12 LastLast
Results 1 to 10 of 11

Thread: Exception Handling in .NET

  1. #1
    Join Date
    Mar 2008
    Location
    The North Pole
    Posts
    13,174
    Blog Entries
    13
    Rep Power
    114

    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:
    [HIGHLIGHT=csharp]
    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.
    }
    [/HIGHLIGHT]
    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!
    Last edited by Xav; 06-20-2008 at 09:27 AM.

    Quote Originally Posted by Jordan View Post
    Good members, like yourself, stick around and post for ages to come!
    Mr. Xav | Blog | Forums

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    Jordan Guest

    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

  4. #3
    Join Date
    Mar 2008
    Location
    The North Pole
    Posts
    13,174
    Blog Entries
    13
    Rep Power
    114

    Re: Exception Handling in .NET

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

    Quote Originally Posted by Jordan View Post
    Good members, like yourself, stick around and post for ages to come!
    Mr. Xav | Blog | Forums

  5. #4
    gaylo565's Avatar
    gaylo565 is offline Programming Professional
    Join Date
    May 2007
    Location
    flagstaff, az
    Posts
    268
    Rep Power
    21

    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.

  6. #5
    Join Date
    Mar 2008
    Location
    The North Pole
    Posts
    13,174
    Blog Entries
    13
    Rep Power
    114

    Re: Exception Handling in .NET

    Hey, thanks gaylo565!

    Quote Originally Posted by Jordan View Post
    Good members, like yourself, stick around and post for ages to come!
    Mr. Xav | Blog | Forums

  7. #6
    Join Date
    Jul 2006
    Location
    Amherst, New York, United States
    Posts
    6,277
    Blog Entries
    26
    Rep Power
    20

    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.

  8. #7
    Join Date
    Mar 2008
    Location
    The North Pole
    Posts
    13,174
    Blog Entries
    13
    Rep Power
    114

    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.

    Quote Originally Posted by Jordan View Post
    Good members, like yourself, stick around and post for ages to come!
    Mr. Xav | Blog | Forums

  9. #8
    Join Date
    Sep 2008
    Location
    Kosovo
    Posts
    4,032
    Rep Power
    44

    Re: Exception Handling in .NET

    haven't seen this one .. +rep from me Xav ..

  10. #9
    Join Date
    Mar 2008
    Location
    The North Pole
    Posts
    13,174
    Blog Entries
    13
    Rep Power
    114

    Re: Exception Handling in .NET

    Cheers, EgZ0N!

    Quote Originally Posted by Jordan View Post
    Good members, like yourself, stick around and post for ages to come!
    Mr. Xav | Blog | Forums

  11. #10
    Join Date
    Oct 2008
    Location
    Istog, Kosova
    Posts
    4,001
    Blog Entries
    1
    Rep Power
    40

    Re: Exception Handling in .NET

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

+ Reply to Thread
Page 1 of 2 12 LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Exception before or after
    By denarced in forum C and C++
    Replies: 1
    Last Post: 10-17-2011, 02:17 PM
  2. Exception handling from a class
    By crazyjackdavis in forum Python
    Replies: 1
    Last Post: 09-29-2011, 12:06 AM
  3. C++ Exception handling
    By SPorg in forum C and C++
    Replies: 2
    Last Post: 08-05-2010, 03:41 PM
  4. General ring0 structured exception handling in asm
    By innerLOL in forum Assembly
    Replies: 1
    Last Post: 02-13-2010, 08:37 PM
  5. linux x86 exception handling
    By innerLOL in forum Linux Programming and Scripting
    Replies: 1
    Last Post: 01-13-2010, 07:47 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts