Next Page
Exception Handling in C#
If you are new to the C# School
This is the 9th in the series of lessons of our C# School. The C# School is a kind of interactive learning platform where those who want to learn .NET with C# can find help and support. With one issue a week, describing some areas of the C# Programming Language with the Microsoft .Net Platform, this is not the same traditional passive tutorial where the author only writes and the reader only reads. There will be exercise problems at the end of each issue, which the reader is expected to solve after reading the issue. The solution to these problems will be provided in the next issue for testing purposes. There is also a dedicated message board attached with the school, where you can ask questions about the article, and the author will respond to your question within 2/3 days. You can send your suggestions, feedback or ideas on how these lessons can be improved to either the Author ( farazrasheed@acm.org)or the WEBMASTER ( info@programmersheaven.com).
For previous lessons:
- Introduction to .Net Framework & C#
- Visual Studio.Net and Hello World Console Application
- C# Language Fundamentals
- Classes and Objects
- Inheritance & Polymorphism in C#
- Structure, Enumeration, Garbage Collection and Nested Classes
- Abstract classes & Interfaces
- Arrays, collections and string Manipulation
Today we will explore exception handling mechanisms in C#. We will start out by looking at the idea behind exceptions and will see how different exceptions are caught. Later, we will explore different features provided and constraints applied by the C# compiler in exception handling. Finally, we will learn how to define our own custom exceptions.
Exceptions Basics
Put simply, exception handling is a mechanism to handle run-time errors in .NET that would otherwise cause your software to terminate prematurely.
The need for Exceptions
Consider the following simple code:
using System;
namespace CSharpSchool
{
class Test
{
static void Main()
{
double p = Divide(3, 5);
Console.WriteLine(p);
}
static double Divide(double a, double b)
{
double c = a/b;
return c;
}
}
}The Divide() method returns the result of the division of the two numbers passed as parameters. The output of the program will be:
0.6
But what if the method Divide() is called in the Main() method as
double p = Divide(3, 0);
There will be no compile time error as both the parameters are cast-able to double. But when the program is executed, the computer will attempt to divide 3 by zero which is not possible. As a result, the program will crash! One way to deal with this is to explicitly check the second parameter and if it is zero return some value to indicate the error
static double Divide(double a, double b)
{
if(d == 0)
{
return 0;
}
double c = a/b;
return c;
}The calling code will be:
static void Main()
{
double p = Divide(3, 5);
if(p == 0)
Console.WriteLine("Error in input");
else
Console.WriteLine(p);
}Here we return a value 'zero' to indicate an error in the input. But the problem is that zero can itself be the result of some division like (0 divided by 4) and in this case the caller may get confused whether the returned value is an error or is a legal result, e.g.
static void Main()
{
double p = Divide(0, 3);
if(p == 0)
Console.WriteLine("Error in input");
else
Console.WriteLine(p);
}In this case the program will display that there is an error in the input, which is clearly not the case. So how do we solve this problem?
Exceptions in C# and .Net
People have worked on this problem and developed a solution in the form of 'Exceptions'. Programmers may define and throw an exception in the case of unexpected events. Below are some important points about exceptions and exception handling mechanisms in C# and .Net
- All exceptions in .Net are objects.
- The System.Exception class is the base class for all exceptions in .Net.
- Any method can raise or throw an exception in the case of some unexpected event during its execution using the throw keyword in C#.
- The thrown exception can be caught or dealt within the calling method using the try...catch block.
- The code that may throw an exception which we want to handle is put in the try block. This is called an attempt to catch an exception.
- The code to handle the thrown exception is placed in the catch block just after the try block. This is called catching the exception. We can define which particular class of exception we want to deal in this catch block by mentioning the name of exception after the catch keyword
- Multiple catch blocks can be defined for a single try block where each catch block will catch a particular class of exception.
- The code that must always be executed after the try or try...catch block is placed in the finally block, placed just after the try or try...catch blocks. This code is guaranteed to always be executed whether the exception occurs or not.
- When an exception is raised during the execution of the code inside the try block, the remaining code in the try block is neglected and the control of execution is transferred to the respective catch or finally block.
- Since exceptions are present in .Net as classes and objects, they follow the inheritance hierarchy. This means that if you write a catch block to handle a base class exception, it will automatically handle all of its sub-class's exceptions. Attempting to catch any of the sub-class's exceptions explicitly after the parent class exception will cause a compile time error.
- The finally block is optional. Exception handling requires a combination of either the try...catch, try...catch...finally or try...finally blocks.
- If you do not catch an exception, the runtime environment (Common Language Runtime or CLR) will catch it on your behalf, causing your program to terminate.
Next Page
|
|
Greg K.
From Pennsylvania, USA (Report as abusive) |
Why "finally"? I don't understand why use "finally" in try-catch. What is the difference between: try { } catch() { } finally { some finally code... } and just this: try { } catch { } some finally code... Whatever is written after the final "catch" is executed anyway, unless the program was terminated, right? So why litter the language with "finally" clause? The C# lessons are excellen! Greg |
|
Kelvin Y
From London (Report as abusive) |
Excellent series. Great job on the series. One of the clearest tutorials I've seen in any language. Greg K. You answered your own question. Code following a try block is not executed if the program terminates. A finaly blocks guarantees that a piece of vital code will execute if execution of a try block begins. Consider to following piece of pseudo-code. try { openfaucet(); watergarden(); } catch(BrokenPipeException e) { ... } finally { closefaucet(); } Without the finally block the closefaucet method would not execute if a broken pipe exception occurred, as execution ends immediately after the exception is handled. The finally block guarantees that the faucet is closed whether the operation in the try block ends sucessfully or not. |
|
Faraz Rasheed
From Karachi (Report as abusive) |
Re: Why use the 'finally' clause? Well, the question why use the 'finally' clause is the 3rd problem of this (9th) lesson's exercise. So work out on it untill next week; when the answer is presented in the 10th lesson |
|
Dingobatt
From Midrand, RSA (Report as abusive) |
Excellent series Love the series. Very well written. I have found the "finally" block to be extremely useful. If I want to exit on exception found, the finally block will contain cleanup code (close db connections, etc.), which would not be executed if it was placed after the try/catch/finally blocks. Basically - the finally block is ALWAYS executed on exiting the try/catch block. |
|
Talon
(Report as abusive) |
Thoroughly suitable Article seemed relatively complete and accurate. Note: I do believe that an exception that is not caught causes code termination. The use of the finally section insures that, inspite of any unforseen exception that may be thrown within the try block, its code (such as releasing unmanaged resources) WILL be run. If the code were placed after the try/catch without being within the finally, the program would terminate without executing the necessary code. I thought the article was quite clear on this matter. |
| View all Rate and comment this article |
Sponsored links
Check For Updates
Easily add update features to your applications. A complete .Net updating solution.
Easily add update features to your applications. A complete .Net updating solution.
Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.
Check Out IT Certification Preparation Materials
Sign Up With SkillSoft & Get Access to Training Materials for Over 50 Professional Certifications.
Sign Up With SkillSoft & Get Access to Training Materials for Over 50 Professional Certifications.
Villanova University Six Sigma & IT Certificate Programs
100% Online programs in Six Sigma, IS Security, CISSP Prep, Business Analysis, Proj. Mgmt. and more!
100% Online programs in Six Sigma, IS Security, CISSP Prep, Business Analysis, Proj. Mgmt. and more!
.Net Localization in three simple steps (WYSIWYG)
Localize .Net, C#/C/C++ & Delphi apps visually. HTML, HTML Help, XML & databases. Try Sisulizer now!
Localize .Net, C#/C/C++ & Delphi apps visually. HTML, HTML Help, XML & databases. Try Sisulizer now!