Thursday, 8 December 2011

c# How to Throw Exception and how to bubble up an Exception


problem

c# - How to throw exceptions, how to bubble up exceptions, how to digg exceptions to find deep error messages and Exceptions.
difficulty level

7/10 :|
compatibility

c#
solution

When you catch an Exception and you want to bubble up (forward) the same exception, you should bubble it up by your own, define it in the 2nd argument of your new Throw Exception. When you bubble up the Exception, you can find it as .InnerException.

try{
  int i=2/0;  //division by zero is not allowed anyway
} catch (Exception e) {
    throw new Exception(
        "Something get wrong, "+
        "error message: "+e.Message,
        e  // here we bubble up the exception
    );
}


The follow code demonstrates how car your dig the InnerException you find all error messages:

string output = "Error messages: ";
Exception exp = exceptionToBubble;
string expmessage = "";

while (exp != null) {
    expmessage = "inner error: " + exp.Message + " " + expmessage;
    exp = exp.InnerException;
}
expmessage += "final error: " + exceptionToBubble.Message;

output += expmessage;

Also, don't forget the .Trace property of the Exception object where show related info.

No comments:

Post a Comment