Related
I have a question reagrding proper programming practice when dealing with exceptions.
We have production code like:
try
{
File.Copy(src,dest);
}
catch(Exception ex)
{
ShowMessageToUser(ex.Message);
}
Is this a good practice? I thought that we should always make use of specialized exceptions and catch them....on the other hand, I do realize that File.Copy can throw several different exceptions and it will be a pain to write a catch block for every exception...? So what should be done in this case....Is there a set of file specific excepion collections that we can use to catch?
Thanks , any comments are welcome.
As a general practice, I would say this is not a good practice. Personally, I would handle this with separate exceptions, and only handle the exceptions you can be handle correctly.
In this specific scenario, I would also avoid this. I would prefer to handle the explicit exception types, if for no other reason than to customize the message to the user.
This is mainly because exception messages are really not intended for an end user - they're messages meant to be interpreted by a developer. I feel that directly showing an exception message to a user, especially for an operation where an exception is likely, is a bad practice.
You should handle each exception, and provide a meaningful message to the user that makes sense in the context of this operation.
File.Copy can only throw 8 types of exceptions - handling every one, with a message, is only 32 lines of code - that's really not that much when you consider the extra benefit of having a clear, meaningful message in all cases presented to the end user.
IO is generally a pain for this reason- there are so many things that can go wrong. It would be best for you to:
Do everything you can to avoid exceptions by checking all parameters before calling File.Copy. Remember that in .Net exceptions can have severe performance costs due to the generation of a stack trace.
Catch the exceptions that you know you are capable of handling. For some exceptions you might want to display an error message and ask the user for new input.
If you can't handle an exception right there, do not catch it! Exception swallowing is the source of all evil. Reporting an error message is only slightly better than exception swallowing and will only confuse the end user.
It may seem like a lot of work, but sometimes a lot of work is necessary to produce a stable program.
You use specialized exceptions in order to perform different actions based on the type of error you got. If all you want is to show the user the default error message... then your code is sufficient.
But let's say for example that you would like to log the exception if it happened because of security issues... you would write something like:
catch (PermissionDeniedException ex)
{
Log(ex.foo);
ShowMessageToUser(ex.Message);
}
catch(Exception ex)
{
ShowMessageToUser(ex.Message);
}
And remember to always go from more specific to more general exceptions.
Yes that's a bad Practice and you should use specific Exceptions and then general Exception lower the catch block.
If you feel that they are too many then you should at least create catch blocks for most Anticipated file Specific Exception and then have usual Exception catch block
Your example is very easy to implement, but hardly best practices. As a general rule
Only catch Exceptions you are actually interested in handling at this point. Let everything else bubble on to be handled elsewhere.
You can also use superclasses to catch a specific group of exceptions.
Do not use exceptions for things that are not errors. For example, if the user supplies the file name for the copy, you can check beforehand if the file exists, instead of relying on an exception. Exceptions are for "exceptional circumstances", not for foreseeable conditions.
If you're hacking a quick script, however, feel free to use the exception as in your example ;-)
Im learning Windows Workflow at the minute and am now looking at exception handling in state machines.
Basically I can see that a FaultHandler can be used to catch a specific exception thrown in an activity.
My question is do I need to specifically catch each type of exception or is there a way I can catch all exceptions with one FaultHandler?
Im sure this isn't best practice(any suggestions there?), but just interested to understand it a bit better.
You should explicitly catch the exceptions you think might occur.
You could have a general purpose exception that handled the base Exception class, but that would potentially hide problems with your code. You would need to log all exceptions and have some way of both letting the user know that there had been a problem and getting this information back to you so that you can correct the problem.
You can catch all if you set the FaultType to System.Exception.
I’m used to having try/catch blocks in every method. The reason for this is so that I can catch every exception at the point of infraction and log it. I understand, from my reading and conversations with others, that this isn’t a popular view. One should only catch what one is prepared to handle. However, if I don’t catch at the point of infraction, then it would be possible to never log that infraction and know about it. Note: When I do catch and don’t handle, I still throw. This allows me to let the exception propagate to something that will handle it, yet still let me log it at the point of infraction.
So... How does one avoid try/catch in every method, yet still log the error at the point at which it occurred?
No, don't catch everything. Exceptions propagate higher up on the stack. All you have to do is make sure that the exception is caught before it gets to the top of the stack.
This means, for instance, that you should surround the code of an event handler with a try/catch block. An event handler may be the "top of the stack". Same for a ThreadStart handler or a callback from an asynchronous method.
You also want to catch exceptions on layer boundaries, though in that case, you might just want to wrap the exception in a layer-specific exception.
In the case of ASP.NET, you may decide to allow ASP.NET Health Monitoring to log the exception for you.
But you certainly don't ever need to catch exceptions in every method. That's a major anti-pattern. I would loudly object to you checking in code with that kind of exception handling.
You can see everything at stack trace - no need to try/catch every method.
Stick to few rules:
Use try/catch only if you want to use a custom exception type
Define a new exception type only if upper levels needs to know that
Try/catch at top level instead of doing that for each method
OK, having read all the answers saying you should have a single try/catch at the top level, I'm going to weigh in with an alternative view.
I wouldn't put a try/catch in every method, far from it. But I would use a try/catch around sections of code that I expected to fail (e.g. opening a file), and where I wanted to add additional information to the exception (to be logged higher up the chain).
A stack trace saying and a message saying "permission denied" might be enough to allow you as a programmer to figure out what went wrong, but my goal is to provide the user with meaningful information, such as "Could not open file 'C:\lockedfile.txt'. Permission denied.".
As in:
private void DoSomethingWithFile(string filename)
{
// Note: try/catch doesn't need to surround the whole method...
if (File.Exists(filename))
{
try
{
// do something involving the file
}
catch (Exception ex)
{
throw new ApplicationException(string.Format("Cannot do something with file '{0}'.", filename), ex);
}
}
}
I'd also like to mention that even the people saying "only have one try/catch" would presumably still use try/finally throughout their code, since that's the only way to guarantee proper cleanup, etc.
Catching and rethrowing an exception that you cannot handle is nothing more than a waste of processor time. If you can't do anything with or about the exception, ignore it and let the caller respond to it.
If you want to log every exception, a global exception handler will do just fine. In .NET, the stack trace is an object; its properties can be inspected like any other. You can write the properties of the stack trace (even in string form) to your log of choice.
If you want to ensure that every exception is caught, a global exception handler should do the trick. In point of fact, no application should be without one.
Your catch blocks should only catch exceptions that you know that you can gracefully recover from. That is, if you can do something about it, catch it. Otherwise, let the caller worry about it. If no callers can do anything about it, let the global exception handler catch it, and log it.
I definitely don't use a try catch wrapper around every method (oddly enough, I did when I first started but that was before I learned better ways).
1) To prevent the program from crashing and the users losing their info, I do this
runProgram:
try
{
container.ShowDialog();
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
if (MessageBox.Show("A fatal error has occurred. Please save work and restart program. Would you like to try to continue?", "Fatal Error", MessageBoxButtons.YesNo) == DialogResult.Yes)
goto runProgram;
container.Close();
}
container is where my application starts so this basically puts a wrapper around my entire app so that nothing causes a crash that can't be recovered. This is one of those rare instances where I don't really mind using a goto (it is a small amount of code and still quite readable)
2) I only catch exceptions in methods where I expect something could go wrong (such as a timeout).
3) Just as a point of readibility, if you have a try catch block with a bunch of code in the try section and a bunch in the catch section, it is better to extract that code to a well named method.
public void delete(Page page)
{
try
{
deletePageAndAllReferences(page)
}
catch (Exception e)
{
logError(e);
}
}
To do it at the point of occurrence, you would still need a try/catch. But you don't necessarily need to catch the exceptions everywhere. They propagate up the call stack, and when they are caught, you get a stack trace. So if a problem emerges, you can always add more try/catches as needed.
Consider checking out one of the many logging frameworks that are available.
I don't think you need to catch everything at the point of infraction. You can bubble up your exceptions, and then use the StackTrace to figure out where the point of infraction actually occurred.
Also, if you need to have a try catch block, the best approach I've heard is to isolate it in a method, as to not clutter the code with huge try catch blocks. Also, make as few statements as possible in the try statement.
Of course, just to reiterate, bubbling up your exceptions to the top and logging the stacktrace is a better approach than nesting try-catch-log-throw blocks all throughout your code.
I would look into using ELMAH for exception handling, which is pretty much a concept of "let exceptions happen". ELMAH will take care of logging them and you can even set it to email you when exceptions for a certain project reach or exceed a specific threshold. In my department, we stay as far away from try/catch blocks as possible. If something is wrong in the application, we want to know right away what the issue is so we can fix it, instead of repressing the exception and handling it in code.
If an exception happens, that means that something isn't right. The idea is to make your application do only what it should do. If it's doing something different and causing exceptions, your response should be to fix the reason it's happening, not let it happen and handle it in code. This is just my/our philosophy and it's not for everyone. But we've all been burned way too many times by an application "eating" an exception for some reason or another and no one knows that something is wrong.
And never, ever, EVER catch a general Exception. Always, always, always catch the most specific exception so that if an exception is thrown, but it's not the type you're expecting, again, you'll know because the app will crash. If you just catch (Exception e), then no matter what type of exception is thrown, your catch block will now be responsible for responding to every single type of exception that could possibly be thrown. And if it doesn't, then you run into the whole "eating" exceptions, where something is going wrong but you never know until it is likely too late.
How does one avoid try/catch in every method, yet still log the error at the point at which it occurred?
It depends on the hosting env. Asp.Net, WinForms, and WPF all have different ways of capturing unhandled exceptions. But once the global handler is passes an exception instance you can determine the point of throw from the exception, as each exception includes a stacktrace.
Realistically, avoid granular try/catches. Allow the exception to traverse upwards in the stack and be caught in as high a level as possible. If you have a specific point of concern, then place logging in the immediate catch, if you are worried about the exception cascading - although you would still be able to resolve these by drilling into the inner exceptions.
Exception handling should not be an afterthought. Make sure that you do it consistently. I have seen a lot of people put a broad try/catch from the beginning to the end of every method and catch the general exception. People think that this helps them get more information, when in fact, it doesn't. More is less in some cases, as less is more. I never get tired of the axiom that "Exceptions should be used to note exceptional behavior." Recover if you can, and try to reduce the number of overall exceptions. Nothing is more frustrating when you are trying to troubleshoot an issue and seeing hundreds of the same NullReferenceException, or similar, when something goes wrong.
Exceptions are implemented so that they have no cost unless thrown.
This means to me that performance ramifications is not a strong argument against. Exceptional conditions usually are ... exceptional.
This question already has answers here:
Best practices for catching and re-throwing .NET exceptions
(11 answers)
Closed 9 years ago.
I'm wondering what the correct way is to pass on an exception from one method to another.
I'm working on a project that is divided into Presentation (web), Business and Logic layers, and errors (e.g. SqlExceptions) need to be passed down the chain to notify the web layer when something goes wrong.
I've seen 3 basic approaches:
try
{
//error code
}
catch (Exception ex)
{
throw ex;
}
(simply rethrow)
try
{
//error code
}
catch (Exception ex)
{
throw new MyCustomException();
}
(throw a custom exception, so that a dependency on the data provider is not passed on)
and then simply
//error code
(not doing anything at all, letting the error bubble up by itself)
Naturally there's some logging happening in the catch block too.
I prefer number 3, while my colleague uses method 1, but neither of us can really motivate why.
What are the advantages/disadvantages of using each method? Is there a better method I don't know of? Is there an accepted Best Way?
If you do nothing you should simply let it go upper where some one will handle it.
You can always handle a part of it (like logging) and re-throw it. You can re-throw by simply sending throw; without having to explicit the ex name.
try
{
}
catch (Exception e)
{
throw;
}
The advantage to handle it is that you can ensure that some mechanism is there to notify you that you have an error where you do not suspect to have one.
But, in some case, let say a Third Party, you want to let the user handle it and when it's that case you should let it continue to bubble up.
I think you should start with a slightly different question
How do I expect other components to interact with exceptions thrown from my module?
If the consumers are quite capable of handling the exceptions thrown by the lower / data layers then quite simply do nothing. The upper layer is capable of handling the exceptions and you should only do the minimum amount necessary to maintain your state and then rethrow.
If the consumers cannot handle low level exceptions but instead need a bit higher level exceptions, then create a new exception class which they can handle. But make sure to pass on the original exception a the inner exception.
throw new MyCustomException(msg, ex);
The correct way to re-throw an exception in C# is like below:
try
{
....
}
catch (Exception e)
{
throw;
}
See this thread for specifics.
Only use try/catch blocks around exceptions you expect and can handle. If you catch something you cannot handle, it defeats the purpose of try/catch which is to handle expected errors.
Catching big exception is rarely a good idea. The first time you catch an OutOfMemoryException are you really going to be able to gracefully handle it? Most API's document the exceptions each method can throw, and those should be the only ones handled and only if you can gracefully handle it.
If you want to handle the error further up the chain, let it bubble up on its own without catching and rethrowing it. The only exception to this would be for logging purposes, but logging at every step is going to do an excessive amount of work. It is better to just document where exceptions your public methods can be expected to allow to bubble up and let the consumer of your API make the decision on how to handle it.
No one has yet pointed out the very first thing you should be thinking of: what are the threats?
When a back-end tier throws an exception, something terrible and unexpected has happened. The unexpected terrible situation might have happened because that tier is under attack by a hostile user. The last thing you want to do in that case is serve up to the attacker a detailed list of everything that went wrong and why. When something goes wrong on the business logic tier the right thing to do is to carefully log all information about the exception and replace the exception with a generic "We're sorry, something went wrong, administration has been alerted, please try again" page.
One of the things to keep track of is all the information you have about the user and what they were doing when the exception happened. That way if you detect that the same user always seems to be causing problems, you can evaluate whether they are likely to be probing you for weaknesses, or simply using an unusual corner of the application that wasn't sufficiently tested.
Get the security design right first, and only then worry about diagnosis and debugging.
I've seen (and held) various strong opinions about this. The answer is that I don't think there currently is an ideal approach in C#.
At one point I felt that (in a Java-minded way) the exception is part of the binary interface of a method, as much as the return type and parameter types. But in C#, it simply isn't. This is clear from the fact that there is no throws specification system.
In other words, you can if you wish take the attitude that only your exception types should fly out of your library's methods, so your clients don't depend on your library's internal details. But few libraries bother to do this.
The official C# team advice is to catch each specific type that might be thrown by a method, if you think you can handle them. Don't catch anything you can't really handle. This implies no encapsulation of internal exceptions at library boundaries.
But in turn, that means that you need perfect documentation of what might be thrown by a given method. Modern applications rely on mounds of third party libraries, rapidly evolving. It makes a mockery of having a static typing system if they are all trying to catch specific exception types that might not be correct in future combinations of library versions, with no compile-time checking.
So people do this:
try
{
}
catch (Exception x)
{
// log the message, the stack trace, whatever
}
The problem is that this catches all exception types, including those that fundamentally indicate a severe problem, such as a null reference exception. This means the program is in an unknown state. The moment that is detected, it ought to shut down before it does some damage to the user's persistent data (starts trashing files, database records, etc).
The hidden problem here is try/finally. It's a great language feature - indeed it's essential - but if a serious enough exception is flying up the stack, should it really be causing finally blocks to run? Do you really want the evidence to be destroyed when there's a bug in progress? And if the program is in an unknown state, anything important could be destroyed by those finally blocks.
So what you really want is (updated for C# 6!):
try
{
// attempt some operation
}
catch (Exception x) when (x.IsTolerable())
{
// log and skip this operation, keep running
}
In this example, you would write IsTolerable as an extension method on Exception which returns false if the innermost exception is NullReferenceException, IndexOutOfRangeException, InvalidCastException or any other exception types that you have decided must indicate a low-level error that must halt execution and require investigation. These are "intolerable" situations.
This might be termed "optimistic" exception handling: assuming that all exceptions are tolerable except for a set of known blacklisted types. The alternative (supported by C# 5 and earlier) is the "pessimistic" approach, where only known whitelisted exceptions are considered tolerable and anything else is unhandled.
Years ago the pessimistic approach was the official recommended stance. But these days the CLR itself catches all exceptions in Task.Run so it can move errors between threads. This causes finally blocks to execute. So the CRL is very optimistic by default.
You can also enlist with the AppDomain.UnhandledException event, save as much information as you can for support purposes (at least the stack trace) and then call Environment.FailFast to shut down your process before any finally blocks can execute (which might destroy valuable information needed to investigate the bug, or throw other exceptions that hide the original one).
I'm not sure that there really is an accepted best practices, but IMO
try // form 1: useful only for the logging, and only in debug builds.
{
//error code
}
catch (Exception ex)
{
throw;// ex;
}
Makes no real sense except for the logging aspect, so I would do this only in a debug build. Catching an rethrowing is costly, so you should have a reason for paying that cost other than just that you like looking at the code.
try // form 2: not useful at all
{
//error code
}
catch (Exception ex)
{
throw new MyCustomException();
}
This one makes no sense at all. It's discarding the real exception and replacing it with one that contains less information about the actual real problem. I can see possibly doing this if I want to augment the exception with some information about what was happening.
try // form 3: about as useful as form 1
{
//error code
}
catch (Exception ex)
{
throw new MyCustomException(ex, MyContextInformation);
}
But I would say in nearly all cases where you are not handling the exception the best form is to simply let a higher level handler deal with it.
// form 4: the best form unless you need to log the exceptions.
// error code. no try - let it percolate up to a handler that does something productive.
Normally you'd catch only exceptions which you expect, can handle and let application work in a normal way further. In case you'd like to have some additional error logging you'll catch an exception, do logging and rethrow it using "throw;" so the stack trace is not modified. Custom exceptions are usually created for the purpose of reporting your application specific errors.
Anyway, I'm a little confused about when to propagate an exception and when to wrap it, and the differences.
At the moment, my understanding tells me that wrapping an exception would involve taking an exception like DriveNotFound (in IO) and then wrap it with the general IOException.
But with the concept of propagating an exception, is this only something that happens if I have an empty catch clause? So in an ASP.NET web app, it would propagate to global.asax. Or in the case of a recently deployed web app, an unhandled HTTPException gave a yellow screen of death and wrote a log to Windows Server (this is a web app I'm rewriting). So the exception happens in a method, it could be handled at the class level, displayed in the page, and then goes up to global.asax or Windows Server.
Why exactly do I want to wrap an exception with a more generic one? The rule is to handle an exception with the most specific type (so DriveNotFound for obviously a drive not found). Also, how would I choose between wrapping and replacing an exception?
Is the exception handling chain just the try and catch (or catches) clauses? I assume from the wording, yes.
Finally, why and how would I want to let an exception propagate up the callstack?
I did read the MS PandP guide on exception handling, but I guess the examples didn't engage me enough to fully understand everything.
This question comes from Enterprise Library the ability to wrap/propagate an exception and etc. It's the propagating I'm not sure about, and the differences in replacing/wrapping an exception.
Also, is it ok to insert complex error handling logic in a catch block (e.g. ifs/elses and things like that).
Thanks
No less than 6 questions :-)
But with the concept of propagating an exception, is this only something that happens if I have an empty catch clause?
An exception will propagate upwards until it is caught by a catch block further up the call stack that handles either that specific exception's type or an exception type nearer the base type of that exception's hierarchy. So, for example, all managed exceptions derive from System.Exception, so a catch block that intercepts System.Exception will catch every managed exception.
Why exactly do I want to wrap an exception with a more generic one?
I'm not sure what you mean by "wrap". Do you mean catch an exception, replace it with another, and add the original as the InnerException property of the new exception? Or something else?
I think there's rarely a good reason to replace an exception with a more generic exception. But you can certainly replace an exception with another exception, for one or more of 3 reasons:
To hide implementation details from the caller.
To improve the level of an abstraction so that it's more meaningful to the caller.
To throw a custom exception that's very specific to the problem in hand.
Also, how would I choose between wrapping and replacing an exception?
I'm sorry, but I still don't understand how you're defining these two as different.
Is the exception handling chain just the try and catch (or catches) clauses?
Here are the basics of what happens when an exception is thrown:
The CLR walks sequentially down the list of Catch blocks within the local Try...End Try block, looking for a local Catch block with an exception filter matching the exception that was thrown.
If a local Catch block has an exception filter that matches the exact exception that was thrown, the code in that Catch block is executed, followed by the code in the Finally block. Then execution continues at the first statement following the End Try.
Alternatively, if the exception that was thrown derives from the exception specified by a local Catch block, the same actions happen as described in the second step. For example, an exception filter that catches ArgumentException will also catch exceptions derived from ArgumentException, such as ArgumentNullException, InvalidEnumArgumentException, DuplicateWaitObjectException, and ArgumentOutOfRangeException.
If no local Catch block matches the exception that was thrown, the CLR walks back up the call stack, method by method, looking for a Catch block that wants to respond to the exception. If no matching Catch block is found in the call stack, the exception is considered to be unhandled.
Alternatively, if a matching Catch block is found somewhere in the call stack, the code in every Finally block between the throw and the catch is executed. This starts with the Finally belonging to the Try block where the exception was thrown and finishes with the Finally in the method below the method where the exception was caught.
After this clean-up has been completed for all methods below where the exception was caught, control is transferred to the Catch block that caught the exception, and this code is executed. Next to run is the Finally block of the Try where the exception was caught. Now that the call stack has been unwound and the error clean-up has been completed, the final step is to continue execution at the first statement following the End Try where the exception was caught.
If code within a Catch block causes another exception to be thrown, the original exception is automatically appended to the new exception using the InnerException property. In this way, exceptions can be stacked without any loss of information.
You should avoid placing clean-up code within a Finally block that might throw an exception, unless that code is within its own Try block. Without this added protection, the CLR behaves as though the new exception was thrown after the end after the Finally block and looks up the call stack for a remote Catch block that wants to respond to the new exception. The original exception will be lost unless the original Catch block saved it.
Finally, why and how would I want to let an exception propagate up the callstack?
Why: Whenever you don't specifically understand the exception and know how to recover from it, you should let it propagate upwards.
How: By only catching exception types that you understand and know how to handle. Occasionally you need the details of any exception in order to do a proper recovery. In this case, you can catch it, do the recovery, then re-throw it by using the throw; statement.
Also, is it ok to insert complex error handling logic in a catch block (e.g. ifs/elses and things like that).
Generally yes, because any new exception caused by code in your Catch block will have the old exception automatically attached to it via the InnerException property. But it's not wise to provoke this mechanism if you can avoid it, so the simpler code you have, the better. Another good reason to keep your Catch code simple is that it often won't go through the same degree of testing as your main-line code.
There is already a rather good question about this with lots of good answers and discussion. See here:
Best Practice for Exception Handling in a Windows Forms Application?
It's all about conveying the right meaning to your callers. I doubt there's cause to wrap a specific exception in a more generic one - that helps no one.
Consider an API that has nothing to do with file access but accesses a config file behind the scenes. If the config file is not present you might wrap the FileNotFoundException in a ConfigurationException so that the correct problem is conveyed to callers.
why and how would I want to let an
exception propagate up the callstack?
You would let an exception propagate if you can't handle it. It's that simple. If there is nothing your code can or should do to work around the exception, then let it propagate. When propagating, be careful how you do so:
throw ex;
is different to:
throw;
The former throws away the old stack trace and creates another from the point the exception is thrown. The latter preserves the original stack trace.
Of course, if you can't handle the exception then you might not bother to catch it in the first place (maybe you want to log though).
I usually do this:
Business logic assemblies (dlls) don't handle exceptions unless they are FULLY understood
Exceptions that are expected but not handleable are wrapped in a single exception type and are allowed to roll up the call stack (i.e., all the different exceptions that can happen during a database interaction are wrapped in a single RepositoryException and thrown)
Unexpected exceptions are allowed to propagate (never include a catch(Exception ex) in a dll)
Exceptions are handled only at the last possible moment (i.e., controller for the UI)
Its usually only far up in the call stack that you know exactly what you're doing (what the current business process is) and how to handle exceptions properly.
This is the best resource I've found for implementing a coherent exception handling strategy in .NET
http://msdn.microsoft.com/en-us/library/cc511522.aspx