How to Use Structured Exception Handling in .NET

How do you handle errors in your code? Are you using Exception Handling or allowing abrupt error information to pop up to the User? This article explains how to use Structured Exception Handling to handle errors more efficiently.

As per .NET terminology, when the normal flow of execution gets affected then an exception has occurred. You can understand this concept with the following examples from C#.

public static void Main( ){
float result = 88/0;
}

When you are trying to divide any number by 0, it is obvious thatit is an error. Since you have not handled this situation above, abrupt error message is thrown to User and application is stopped. Instead use try..catch block as shown below. Define your code inside try block and catch exceptions in catch block.

public static void Main( ){
try{
float result = 88/0;
}
catch(DivideByZeroException dbzExp){
Console.WriteLine(“A Number is divided by 0 in Main Method of Test Class:”,dbzExp);
}
catch(NumberFormatException nfExp){
Console.WriteLine(“Number Format Exception occurred in Main Method of Test Class:”,
nfExp);
}
catch(Exception exp){
Console.WriteLine(“Exception occurred in Main Method of Test Class:”, exp);
}
}

When the exception occurs in try block, catch block defining the most specific exception will be executed. If there is no specific match then catch block handling Exception, the super class of all exceptions will be executed. In this example, which catch block will be executed? Catch block handling DivideByZeroException will be triggered.

If the exception occurs inside a function which doesn’t handle that exception, then the exception is passed to the Caller, who can handle it in three different ways:

• Caller Beware: Caller doesn’t handle the exception at all. This might lead to problems and User will not be provided sufficient information about the exception.

• Caller Confuse: Caller catches the exception, does required cleanup and throws the exception. But this does not provide additional information about the exception.

• Caller Inform: Caller catches the exception, wraps into another exception with additional information recorded and throws it.

Handling exceptions alone will not solve your purpose in certain cases. For instance, if you have a file (unmanaged resource) open in your program and an exception occurs even before you have closed the file. Then what happens? Information is provided in the console and the application stops. The file is no longer in use. But the file is still not closed. Hence memory will not be freed. How will you solve this problem? There will be certain block of code that you want to execute irrespective of Exception occurrence. File closing is one such piece of code. You can write such code into finally block, as shown below:

public static void Main( ){
FileStream testFile = new FileStream(“temp.txt”, FileMode.Open);
try{
//do some file processing here
float result = 100/0;
testFile.Close();
}
catch(Exception exp){
Console.WriteLine(“Exception occurred in Main Method of Test Class:”, exp);
}
finally {
testFile.Close();
}
}

Here testFile.Close() inside try block will never be executed. However code in finally block will be executed and therefore the file will be freed.

Till now you were focusing on scenarios which has pre-defined exceptions defined. What if your business scenario requires you to raise an exception very specific to your requirement? For example, you develop banking application wherein the minimum amount in your account after withdrawal should be 10000 bugs. If it is less than that, then you have to throw an exception. .NET provides this facility using User-Defined Exception Classes. Here is an example:

public class customException:Exception{
public customException() { }
public customException(String errorMsg) : base(errorMsg) { }
public customException(String errorMsg, Exception inner) : base(errorMsg, inner) { }
}

public class useCustomException{
public static void Main(){
try{
//define the processing logic
If(conditionFailed)
throw (new customException(“Minimum balance amount not maintained”));
}
catch(customException cusExp){
Console.WriteLine(“User Defined Exception Occurred:”, cusExp);
}
}
}

Always use exceptions to provide additional information with which you can easily trap the error occurrence. But don’t use exceptions for expected events. User Defined Exceptions have a considerable overhead. Hence use them only on need.


FREE Subscription

Subscribe to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.

Name:
Email:

Note : We never rent, trade, or sell my email lists to
anyone. We assure that your privacy is respected
and protected.

Visit .NET Programming Tutorial Homepage

______________________________________________________

Recommended Resource

| Additional Ways of Ensuring Security in .NET | Memory Lifecycle in .NET – An Overview | Few Best Coding Practices for ASP .NET | Handling Session Efficiently Using SQLSERVER State Management in .NET | How to Restrict a Program to Single Instance in .NET? | How to Use Structured Exception Handling in .NET | Understanding Boxing Versus Unboxing in .NET | Understanding Different Levels of Security in .NET | Understanding the Disadvantages of Memory Management in .NET | Using Membership API for Secured Coding in .NET |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2022 - All Rights Reserved.