Hey:)
Is there any way to catch a handled exception globally? I know we can catch unhandled exceptions with " AppDomain.CurrentDomain.UnhandledException" and "Application.ThreadException", but I would like to add some handling to the exceptions I already caught (such as writing to log, etc)
thanks
In general, you probably want to catch exceptions at the lowest possible level in your code. The closer they're handed relative to where the exception occurs, the better chance that you have to fix the problem that caused them.
If you can't take any corrective action at this level that has a hope of fixing the problem causing the exception, you should not be handling it at all. Just let the exception bubble up, and handle it globally like you want.
That being said, if you've have handled the exception at a lower level, the only way you're going to be able to catch it at a higher level is if you rethrow it from the Catch block at the lower level.So, for example:
try
{
//your code
}
catch (SomeException e)
{
//take any relevant handling measures
//rethrow the exception
throw;
}
Of course, this would technically mean that the exception is unhandled by this Try/Catch block at the lower level, but that's the only way you're going to have anything to catch at a higher level.
For more information on rethrowing exceptions, see:
Why Re-throw Exceptions?
http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx
http://msdn.microsoft.com/en-us/library/xhcbs8fz.aspx
You can rethrow same exception and catch it in calling module / logging module and then log it.
For example :
private void DivideByZero()
{
try
{
int x = 2/0;
}
cath(Exception ex)
{
Console.Writeline(ex.ToString());
throw;
}
}
void Main(string[] a)
{
try
{
DivideByZero();
}
catch(Exception x)
{
// write logging code here ..
}
}
No, there is not global exception event. That would be very dangerous, you would catch all sorts of internal exceptions from other modules that was not ment for public use. It would also potentially drown your logs with exceptions.
You should be more structured about your exception handling to achieve the same effect. Encapsulate the actual handling of exceptions and do minimal work in the actual catch block. Either by just have a "HandleException" method somewhere that you pass every exception too. You might also have a look at the Exception Handling block in Enterprise library.
Related
What is the scope of exception handling in C#. I am currently reviewing some code from another programmer on my team and he has a function laid out somewhat like this:
private void function1() {
try {
function2();
}
catch (Exception ex) {
EmailException(ex.message());
}}
private void function2() {
try {
// Do stuff
}
catch (Exception ex) {
// Handle it here
}}
The bulk of the processing code is in function2. However his reporting handling is in function1. Will an exception in function2 kick back to the function1 handler that sends the report?
Edit:
Thanks for your responses, they all were very helpful!
Assuming // Handle it here does not rethrow the exception, function1 will never see the original exception.
It is possible function2 will raise a new issue in its catch though, much like it's possible EmailException could err in function1.
Only if
a) function2 re-throws the original exception with throw or a new exception with throw new ...
b) an unexpected exception occurs inside function2's catch block or after it (which actually in this case is impossible since the catch block is the last thing that happens in function2).
No, an exception propagates only until it is caught.
However, you can re-throw the exception at the end of the catch in function2, leading to the desired behaviour:
private void function2() {
try {
// Do stuff
}
catch (Exception ex) {
// Handle it here
throw; // <- Re-throw the exception.
// Note this is different from `throw ex;`
}
}
Will an exception in function2 kick back to the function1 handler that sends the report?
No unless
An exception occurs outside of function2's try block
An exception occurs inside the function2 exception block
An exception is thrown e.g. trow or trow ex from function2's exception block
An exception is raised in function2's try block that is automatically retrown like ThreadAbortException
In .net, when an exception occurs, the system will search through the nested try blocks on the stack to determine if there is a catch block that can catch the exception. This occurs before any finally blocks run. If there isn't any block that can catch the exception, the system will invoke an "unhandled exception" handler without running any finally blocks.
If the system that does determine that there is a block that can catch the exception, it will start unwinding the stack and run finally blocks associated with inner try blocks until either it has unwound the stack all the way to the catch block it found, or an exception gets thrown in the execution of a finally block. In the latter situation, the previous exception will be abandoned and not processed further; exception handling will start afresh with the newly-thrown exception.
Although there is a semantic difference between wanting to catch an exception, versus merely wanting to act upon it (but let it be regarded as uncaught), there is no clean way to express that distinction in C#; code which catches an exception is expected to resolve it. The best one can do in C# is use a catch (indicating to the system's exception-processing logic to think one is going to catch the exception) and then use a throw, to indicate one doesn't want to resolve it after all (this will occur after inner "finally" blocks have run). In some other languages such as vb.net, it is possible to act upon exceptions, without catching them, before finally blocks run. While there aren't a huge number of cases where a catch and throw is different from capturing an exception without catching it, there are few cases where the distinction matters. If one is using C# and one wishes to avoid being hostile to surrounding code which might want to capture exceptions from inner code before finalizer blocks run, the best approach is probably to write an exception-handling wrapper method written in vb (or have someone else do it), compile it to a DLL, and then use lambdas to feed such a function methods for it to invoke within a suitable try/filter/catch/finally block.
Is it correct to catch each exception with Exception class ??? If not then what should be the correct sequence to catch exception within try catch block?
e.g
try{
.
.
some code
.
}
catch(Exception ex)
{
throw ex;
}
No, this is wrong.
Catching only to throw again is pointless.
It's rethrowing incorrectly, which leads to losing the stack trace. The right way to rethrow (when rethrowing makes sense, that is), is simply: throw;
If you want to catch one exception and then throw another, you should keep the first one as an inner exception of the second. This is done by passing it in to the constructor.
Bottom line: Only catch the exceptions that you know what to do with.
If you are throwing the exception right after you catch it -- that is essentially the same as not having a try / catch block at all.
Catch specific exceptions that might occur.
For instance, you try to save a file but for some reason it cannot be written:
try
{
SaveFile();
}
catch(FileIsReadOnlyException)
{
//do whatever to recover
}
catch(Exception ex)
{
//If we hit the generic exception, we're saying that we basically have
//no idea what went wrong, other than the save failed.
//
//Depending on the situation you might want to sink and log it, i.e. do nothing
//but log it so you can debug and figure out what specific exception handler to
//add to your code -- or you might want to try to save to a temporary file and
//exit the program.
//
//If you were UpdatingAnAdvertisement() or doing something else non-critical
//to the functioning of the program, you might just let it continue and
//do nothing.
//
//In that case, you can just omit the generic catch.
}
In my opinion, you should generally try and catch exceptions that you would expect to come out of the code you call in the try block, and let the rest get caught elsewhere. For instance:
try
{
// ... some code that you know may throw ArgumentException or any other known exceptions
}
catch (ArgumentException ex)
{
// ... handle the exception with a good idea of why it was thrown
}
In the catch block, you now can handle the error in a clean, specific way knowing that an invalid argument was passed somewhere in the try block. For example, you could alert the user that they have supplied an invalid argument.
If something happened that you didn't expect (e.g. a NullReferenceException) you probably don't know how to recover from it, so by not catching it you delegate responsibility to the consumer of your component to handle exceptional situations in general.
In short, you should catch exceptions when you know how to handle or correct the error, and allow unknown errors to be caught higher-up the call chain
Make sense?
Always catch most specific exceptions first.
try
{
// some file system code
}
catch (DirectoryNotFoundException e1)
{
// do something about it
}
catch (IOException e2)
{
// do something else about it
}
catch (Exception e)
{
// most generic catch - probably just dump onto screen or error log
}
Rethrowing is made for easier debugging - that is not a way to tell user about the error. The right way to do it:
try
{
// some code that does X
}
catch (Exception e)
{
throw new Exception("describe X and parameters to it where applicable", e);
}
It's not so much that it's incorrect, as that re-throwing the exception is not what you should be doing. There's a host of reasons that re-throwing it is bad mojo and they touch things like maintainability, performance and good coding practices. Unfortunately, the compiler allows it.
As for when you should be catching the exception,a good rule of thumb is that the exception needs to be caught at the point that you want your code to HANDLE the exception.
I am reading C# article.It suggests that
At the end of the catch block, you have three choices:
• Re-throw the same exception, notifying code higher up in the call stack of the
exception.
• Throw a different exception, giving richer exception information to code higher up in
the call stack.
• Let the thread fall out of the bottom of the catch block.
I am unable to understand the points.It would be a great help, if you clarify it by giving simple example.
Thanks in advance.
Update :
When i need to handle rethrown exception ,do i need to have nested try .. catch blocks like
try
{
try
{
}
catch(InvalidOperationException exp)
{
throw;
}
}
catch(Exception ex)
{
// handle the exception thrown by inner catch block
// (in this case the "throw" clause inside the inner "catch")
}
}
Well, here are those different options in code:
Option 1: Rethrow
try
{
// Something
}
catch (IOException e)
{
// Do some logging first
throw;
}
Option 2: Throw a different exception
try
{
// Something
}
catch (IOException e)
{
// Do some logging first
throw new SorryDaveICantDoThatException("Oops", e);
}
Option 3: Let the thread fall out of the bottom
try
{
// Something
}
catch (IOException e)
{
// Possibly do some logging, and handle the problem.
// No need to throw, I've handled it
}
EDIT: To answer the extra question, yes - if you need to handle a rethrown exception, that needs to be handled in an outer scope, exactly as shown in the question. That's very rarely a good idea though. Indeed, catch blocks should relatively rare in the first place, and nested ones even more so.
These are the choices. Difference between 1 and 2 is that if an exception is thrown and you want to debug to the position is it thrown, you will get there with option 1
(all the way down in the try block at the specific object). With option 2 you will and up only at that line (throw new Exception2())
3 is when you want to ignore the exception and just continue
//1
catch (Exception ex)
{
throw;
}
//2
catch (Exception ex)
{
throw new Exception2();
}
//3
catch (Exception ex)
{
}
return something;
In most production systems the last thing you want is a truly unhandled exception. This is why you typically try and catch statements.
You might be wondering why you would want to throw an error you've caught, and here are a few real world examples.
You've caught an exception in a WCF Application, logged the exception, then thrown a faultException instead to be returned to the WCF client. In the same way you might have a traditional asmx, caught an exception, then thrown a SOAP exception back to the client. Point is certain exceptions need to abide by certain rules: a standard .net exception would not be digested well by a WCF client for example.
You've caught an exception somewhere deep inside your code, logged the exception and possibly even taken some action. But higher up in your code you have another routine that is also waiting for exceptions, at this point higher up, an exception could easily change the business workflow. By catching the exception lower down, the code higher up is not aware of any exception, so you need to throw the exception back out to be caught higher up, so that the code you wrote up there can adjust the workflow. Ofc none of this happens by magic, it all has to be coded, and differant programmers use differant techniques.
You might also want to catch an exception around just 1 or a few statements, for example getting a configuration value from an XML file, if something goes wrong, .net might just return object reference not set. You might catch this, then rethrow the exception as "Configuration Value : Customer Name not provided".
Hope this helps.
rethrow the same exception:
try
{
// do something that raises an exception
}
catch (SomeException ex)
{
// do something with ex
throw;
}
throw a different exception
try
{
// do something that raises an exception
}
catch (SomeException ex)
{
// do something with ex
throw new SomeOtherException(ex); // NOTE: please keep ex as an inner exception
}
let the thread fall out:
try
{
// do something that raises an exception
}
catch (SomeException ex)
{
// do something with ex
}
// the code will finish handling the exception and continue on here
1) Re-throw
try
{
...
}
catch (Exception e)
{
...
throw;
}
2) Throw a new exception
try
{
...
}
catch (Exception e)
{
...
throw new NewException("new exception", e);
}
3) Fall out
try
{
...
}
catch (Exception e)
{
...
}
You could also return in the catch block, so there is that 4th option. Return false, return null, etc... (even return a default value.)
Letting the catch block fall through implies that you have successfully dealt with the Exception that was raised in your try block. If you haven't, better rethrow, or fail in some other way.
this isn't c# specific, it's true of any programming language (call them exceptions, call them errors, call them whatever you want).
So, the answer to you question is that this is a basic premise of all programming and you must determine the correct action to take in your code, given the error, the circumstance and the requirements.
Taylor,
As you are learning about Exception handling I would like to add my 2 cents. Exception throwing is very expensive ( expensive being memory hogging of course ) so in this case you should consider assigning the error message to a string and carry it forward through the application to the log or something.
for example:
string errorMessage = string.empty;
try
{
...
}
catch(Exception e)
{
errorMessage = e.Message + e.StackTrace;;
}
This way you can carry this string anyway. This string can be a global property and can be emailed or logged in text file.
I think that there is something to add to the great answers we've already got here.
It may be part of your overall architectural design (or not) but what I've always observed is that you typically only catch where you can add value (or recover from the error) - in other words, not to try...catch...re-throw multiple times for a single operation.
You should normally plan a consistent pattern or design for how you handle exceptions as part of your overall design. You should always plan to handle exceptions in any case, unhandled exceptions are ugly!
Suppose I have the following two classes in two different assemblies:
//in assembly A
public class TypeA {
// Constructor omitted
public void MethodA
{
try {
//do something
}
catch {
throw;
}
}
}
//in assembly B
public class TypeB {
public void MethodB
{
try {
TypeA a = new TypeA();
a.MethodA();
}
catch (Exception e)
//Handle exception
}
}
}
In this case, the try-catch in MethodA just elevates the exception but doesn't really handle it. Is there any advantage in using try-catch at all in MethodA? In other words, is there a difference between this kind of try-catch block and not using one at all?
In your example, there is no advantage to this. But there are cases where it is desirable to just bubble up a specific exception.
public void Foo()
{
try
{
// Some service adapter code
// A call to the service
}
catch (ServiceBoundaryException)
{
throw;
}
catch (Exception ex)
{
throw new AdapterBoundaryException("some message", ex);
}
}
This allows you to easily identify which boundary an exception occurred in. In this case, you would need to ensure your boundary exceptions are only thrown for code specific to the boundary.
Yes there is a difference. When you catch an exception, .NET assumes you are going to handle it in some way, the stack is unwound up to the function that is doing the catch.
If you don't catch it will end up as an unhandled exception, which will invoke some kind of diagnostic (like a debugger or a exception logger), the full stack and its state at the actual point of failure will be available for inspection.
So if you catch then re-throw an exception that isn't handled elsewhere you rob the diagnostic tool of the really useful info about what actually happened.
With the code the way you've written it for MethodA, there is no difference. All it will do is eat up processor cycles. However there can be an advantage to writing code this way if there is a resource you must free. For example
Resource r = GetSomeResource();
try {
// Do Something
} catch {
FreeSomeResource();
throw;
}
FreeSomeResource();
However there is no real point in doing it this way. It would be much better to just use a finally block instead.
Just rethrowing makes no sense - it's the same as if you did not do anything.
However it gets useful when you actually do something - most common thing is to log the exception. You can also change state of your class, whatever.
Taken as-is, the first option would seem like a bad (or should that be 'useless'?) idea. However, it is rarely done this way. Exceptions are re-thrown from within a Catch block usually under two conditions :
a. You want to check the exception generated for data and conditionally bubble it up the stack.
try
{
//do something
}
catch (Exception ex)
{
//Check ex for certain conditions.
if (ex.Message = "Something bad")
throw ex;
else
//Handle the exception here itself.
}
b. An unacceptable condition has occurred within a component and this information needs to be communicated to the calling code (usually by appending some other useful information or wrapping it in another exception type altogether).
try
{
//do something
}
catch (StackOverflowException ex)
{
//Bubble up the exception to calling code
//by wrapping it up in a custom exception.
throw new MyEuphemisticException(ex, "Something not-so-good just happened!");
}
Never do option A. As Anton says, it eats up the stack trace. JaredPar's example also eats up the stacktrace. A better solution would be:
SomeType* pValue = GetValue();
try {
// Do Something
} finally {
delete pValue;
}
If you got something in C# that needs to be released, for instance a FileStream you got the following two choices:
FileStream stream;
try
{
stream = new FileStream("C:\\afile.txt");
// do something with the stream
}
finally
{
// Will always close the stream, even if there are an exception
stream.Close();
}
Or more cleanly:
using (FileStream stream = new FileStream("c:\\afile.txt"))
{
// do something with the stream
}
Using statement will Dispose (and close) the stream when done or when an exception is closed.
When you catch and throw, it allows you to set a breakpoint on the throw line.
Re-throwing exceptions can be used to encapsulate it into generic exception like... consider following example.
public class XmlException: Exception{
....
}
public class XmlParser{
public void Parse()
{
try{
....
}
catch(IOException ex)
{
throw new XmlException("IO Error while Parsing", ex );
}
}
}
This gives benefit over categorizing exceptions. This is how aspx file handlers and many other system code does exception encapsulation which determines their way up to the stack and their flow of logic.
The assembly A - try catch - block does not make any sense to me. I believe that if you are not going to handle the exception, then why are you catching those exceptions.. It would be anyway thrown to the next level.
But, if you are creating a middle layer API or something like that and handling an exception ( and hence eating up the exception) in that layer does not make sense, then you can throw your own layer ApplicationException. But certainly rethrowing the same exception does not make sense.
Since the classes are in 2 different assemblies, you may want o simply catch the exception for logging it and then throw it back out to the caller, so that it can handle it the way it sees fit. A throw instead of a throw ex will preserve contextual information about where the exception originated. This can prove useful when your assembly is an API/framework where in you should never swallow exceptions unless its meaningful to do so but helpful nonetheless in trouble shooting if it's logged for example to the EventLog.
You can use try{} catch(ex){} block in Method A only if you could catch the specific exception which can be handled in MethodA() (for eg: logging ).
Another option is chain the exception using the InnerException property and pass it to the caller. This idea will not kill the stack trace.
Should I catch exceptions for logging purposes?
public foo(..)
{
try
{
...
} catch (Exception ex) {
Logger.Error(ex);
throw;
}
}
If I have this in place in each of my layers (DataAccess, Business and WebService) it means the exception is logged several times.
Does it make sense to do so if my layers are in separate projects and only the public interfaces have try/catch in them?
Why? Why not? Is there a different approach I could use?
Definitely not. You should find the correct place to handle the exception (actually do something, like catch-and-not-rethrow), and then log it. You can and should include the entire stack trace of course, but following your suggestion would litter the code with try-catch blocks.
Unless you are going to change the exception, you should only log at the level where you are going to handle the error and not rethrow it. Otherwise your log just has a bunch of "noise", 3 or more of the same message logged, once at each layer.
My best practice is:
Only try/catch in public methods (in general; obviously if you are trapping for a specific error you would check for it there)
Only log in the UI layer right before suppressing the error and redirecting to an error page/form.
The general rule of thumb is that you only catch an exception if you can actually do something about it. So at the Business or Data layer, you would only catch the exception in situation's like this:
try
{
this.Persist(trans);
}
catch(Exception ex)
{
trans.Rollback();
throw;
}
My Business/Data Layer attempts to save the data - if an exception is generated, any transactions are rolled back and the exception is sent to the UI layer.
At the UI layer, you can implement a common exception handler:
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Which then handles all exceptions. It might log the exception and then display a user friendly response:
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
LogException(e.Exception);
}
static void LogException(Exception ex)
{
YYYExceptionHandling.HandleException(ex,
YYYExceptionHandling.ExceptionPolicyType.YYY_Policy,
YYYExceptionHandling.ExceptionPriority.Medium,
"An error has occurred, please contact Administrator");
}
In the actual UI code, you can catch individual exception's if you are going to do something different - such as display a different friendly message or modify the screen, etc.
Also, just as a reminder, always try to handle errors - for example divide by 0 - rather than throw an exception.
It's good practice is to translate the exceptions. Don't just log them. If you want to know the specific reason an exception was thrown, throw specific exceptions:
public void connect() throws ConnectionException {
try {
File conf = new File("blabla");
...
} catch (FileNotFoundException ex) {
LOGGER.error("log message", ex);
throw new ConnectionException("The configuration file was not found", ex);
}
}
Use your own exceptions to wrap inbuild exception. This way you can distinct between known and unknown errors when catching exception. This is usefull if you have a method that calls other methods that are likely throwing excpetions to react upon expected and unexpected failures
you may want to lookup standard exception handling styles, but my understanding is this: handle exceptions at the level where you can add extra detail to the exception, or at the level where you will present the exception to the user.
in your example you are doing nothing but catching the exception, logging it, and throwing it again.. why not just catch it at the highest level with one try/catch instead of inside every method if all you are doing is logging it?
i would only handle it at that tier if you were going to add some useful information to the exception before throwing it again - wrap the exception in a new exception you create that has useful information beyond the low level exception text which usually means little to anyone without some context..
Sometimes you need to log data which is not available where the exception is handled. In that case, it is appropriate to log just to get that information out.
For example (Java pseudocode):
public void methodWithDynamicallyGeneratedSQL() throws SQLException {
String sql = ...; // Generate some SQL
try {
... // Try running the query
}
catch (SQLException ex) {
// Don't bother to log the stack trace, that will
// be printed when the exception is handled for real
logger.error(ex.toString()+"For SQL: '"+sql+"'");
throw; // Handle the exception long after the SQL is gone
}
}
This is similar to retroactive logging (my terminology), where you buffer a log of events but don't write them unless there's a trigger event, such as an exception being thrown.
If you're required to log all exceptions, then it's a fantastic idea. That said, logging all exceptions without another reason isn't such a good idea.
You may want to log at the highest level, which is usually your UI or web service code. Logging multiple times is sort of a waste. Also, you want to know the whole story when you are looking at the log.
In one of our applications, all of our pages are derived from a BasePage object, and this object handles the exception handling and error logging.
If that's the only thing it does, i think is better to remove the try/catch's from those classes and let the exception be raised to the class that is responsible on handling them. That way you get only one log per exception giving you more clear logs and even you can log the stacktrace so you wont miss from where the exception was originated.
My method is to log the exceptions only in the handler. The 'real' handler so to speak. Otherwise the log will be very hard to read and the code less structured.
It depends on the Exception: if this actually should not happen, I definitely would log it. On the other way: if you expect this Exception you should think about the design of the application.
Either way: you should at least try to specify the Exception you want to rethrow, catch or log.
public foo(..)
{
try
{
...
}
catch (NullReferenceException ex) {
DoSmth(e);
}
catch (ArgumentExcetion ex) {
DoSmth(e);
}
catch (Exception ex) {
DoSmth(e);
}
}
You will want to log at a tier boundary. For example, if your business tier can be deployed on a physically separate machine in an n-tier application, then it makes sense to log and throw the error in this way.
In this way you have a log of exceptions on the server and don't need to go poking around client machines to find out what happened.
I use this pattern in business tiers of applications that use Remoting or ASMX web services. With WCF you can intercept and log an exception using an IErrorHandler attached to your ChannelDispatcher (another subject entirely) - so you don't need the try/catch/throw pattern.
You need to develop a strategy for handling exceptions. I don't recommend the catch and rethrow. In addition to the superfluous log entries it makes the code harder to read.
Consider writing to the log in the constructor for the exception. This reserves the try/catch for exceptions that you want to recover from; making the code easier to read. To deal with unexpected or unrecoverable exceptions, you may want a try/catch near the outermost layer of the program to log diagnostic information.
BTW, if this is C++ your catch block is creating a copy of the exception object which can be a potential source of additional problems. Try catching a reference to the exception type:
catch (const Exception& ex) { ... }
This Software Engineering Radio podcast is a very good reference for best practices in error handling. There are actually 2 lectures.
It's bad practice in general, unless you need to log for very specific reasons.
With respect in general log exception, it should be handled in root exception handler.