Related
It's often said that you shouldn't use exceptions for regular error handling because of bad performance. My guess is that that bad performance is caused by having to instantiate a new exception object, generate a stack trace, etc. So why not have lightweight exceptions? Code like this is logically sound:
string ageDescription = "Five years old";
try {
int age = int.Parse(ageDescription);
}
catch (Exception) {
// Couldn't parse age; handle parse failure
}
And yet we're recommended to use TryParse instead to avoid the overhead of the exception. But if the exception were just a static object that got initialized when the thread started, all the code throwing the exception would need to do is set an error code number and maybe an error string. No stack trace, no new object instantiation. It would be a "lightweight exception", and so the overhead for using exceptions would be greatly reduced. Why don't we have such lightweight exceptions?
The exception object instantiation is the smallest problem in the whole case. The real performance killer is that the control flow must stop executing your program and has to look up the call stack for possible handlers (catch blocks) that can catch the thrown exception, then it has to execute the correct ones (and their finally blocks), rethrow exceptions when told so and then continue executing the program on the right place, i.e. after the last handler. Your idea of "lightweight" exceptions would change nothing of this, it would even slow down creation of threads, because it would have to create and store the exception object, and would prevent exception filtering by type, which is now possible.
By using TryParse, you avoid all this by a simple conditional clause, also you actually write less code and it is much easier to read and reason about.
Exceptions are for exceptional cases and in such scenarios, they provide lots of useful information for logs/debugger.
The performance hit isn't just because you're creating a new Exception object. A lot of it has to do with the conditional unwinding of the stack that needs to be done when an exception occurs.
For example, think about the work that would have to be done when you have exception handlers that catch different kinds of exceptions. At each point in the stack, as it's unwound from callee to caller, the language must do a type check to see not only if the exception can be handled, but what the most appropriate handler is. That's a significant amount of overhead in its own right.
If you really want to be lightweight, you should return a result from your functions -- that's what Int32.TryParse() does. No stack unwinding, no type checking, just a simple condition which can easily be optimized for.
EDIT: One somewhat interesting thing to note is that C# was created after Java. Java has a couple of interesting constructs which cause exception handling to be more complicated than what we see in C#, namely checked exceptions and the throws keyword. Kind of interesting reads. I'm (personally) glad that C# didn't include this "feature". My guess is that they bifurcated their exception handlers to boost performance. In the real world, as I understand it, a LOT of developers just end up specifying throws exception in their function declarations.
You should use int.TryParse in your case. And it is faster and more readable to test some conditions then to throw and catch exception. Use exceptions for exceptional situations not for regular validation.
The problem with exceptions isn't just generating the exception itself, that's honestly not even the most time consuming part. When you throw an exception (after it has been created) it needs to unwind the stack going through each scope level, determining if that scope is a try/catch block that would catch this exception, update the exception to indicate it went through that section of the stack, and then tearing down that section of the stack. And then of course there are all of the finally blocks that may need to be executed. Making the Exception itself store less information wouldn't really simplify any of that.
Because the utility offered by the "heavyweight" exceptions is exceptionally (ha ha) useful. I can't tell you how often I've wanted the ability to dump something like a stack trace in C land without having to ask people to yank out a debugger.
Generating things like the stack trace after the fact (i.e. after the exception has been caught on demand) are infeasible because once the exception has been caught, the stack has been unwound -- the information is gone. You want information about the point of failure; so the data must be collected at the point of failure.
As for the "new object instantiation" -- that is so cheap in comparison to other expensive exception features (unwinding the stack, stack trace, multiple function exit points, etc.) that it isn't worth worrying about.
You're not recommended to use TryParse instead of Parse because of performance. If there's any chance a parse can fail (because it's user generated input for example) then the failure to parse is not exceptional, it's to be expected. As the name implies, exceptions are for exceptional circumstances. For stuff that should have been caught earlier, but wasn't, so unexpected that you can't really continue.
If a function expects an object but instead null is passed in, then it's up to the designer of the method what the right thing to do is in this case. If the parameter is an optional override for a default, the program ca continue and use the default or ignore the parameter. But otherwise, the program should simply throw a ArgumentNullException.
Performance shouldn't be a consideration at all when deciding to use exceptions or not. It's a matter of intent and purpose. They're not even that slow, sure they're many times slower than adding two integers, but I can still throw 50,000 exceptions per second on my aging Core 2 Duo. If the use of exceptions ever becomes a bottleneck, you're not using them in the right way.
I've read that throwing exceptions is an expensive operation. However, doesn't creating your own exceptions make your code more expressive and readable?
Some of my coworkers suggest that you should just use System.Exception and insert your custom text into the message instead of creating a new custom exception.
I'm interested in other opinions. Appreciate any suggestions.
Do not throw System.Exception. Ever.
The problem with it resides in the calling code. It is a bad practice to catch the general Exception object for many reasons. If you throw an instance of the Exception base class, then calling code has no choice but to catch Exception if they want to handle it. This forces the calling code to use a bad practice.
Also, the calling code has no reliable means of distinguishing what the exception was, if all it gets is Exception.
It is typically best to use one of the pre-defined exceptions if any are applicable (ArgumentException, InvalidOperationException, etc.). If none correctly describe the situation, then a custom exception class is a perfectly good way to go.
It's the overhead of throwing an exception itself (creating the object, walking the stack, etc.) that's costly. Making your own exception class adds almost no overhead, so if you're going to throw an exception, don't make it new Exception("message")!
Exceptions aren't meant to be read by people (though their messages and stack traces are read by people), they're meant to be read by code. If there's something your code can do in response to a custom exception, by all means go for it. But the exception is just destined to be logged, there's no point to making a custom one.
The overhead of custom exceptions is that they're another thing to maintain and test. If an existing exception is suitable, use that instead. (E.g., ArgumentNullException instead of ZipCodeNullException.)
If there's any reason for your exception to be caught and handled differently from standard Exceptions, then you should create your own class.
If there's any reason for your exception to take different arguments (e.g. to produce a specially-formatted message based on a set of arguments that you're often likely to have), then you should create your own class.
In any other case, you're safe just using Exception. Generally speaking, it doesn't really cost any more to instantiate or throw a custom exception than a standard one, at least not compared with the expense of throwing an exception in the first place. Exceptions, by definition, should be exceptional, and therefore performance during the throwing of an exception is a non-issue. The point is to have all the information you need when the time comes to look at why that exception was thrown.
You should never throw a System.Exception, because then the only way to catch is is by catch(System.Exception). It's very bad practice to catch a blanket exception like that. You should catch specific exceptions, which give you a way to properly handle it without crashing the software. By generating custom exceptions, you give yourself a way to potentially recognize and recover from them.
For example, if your code means to open a file, and you get an unknown exception, how do you recover from it? However, if you catch a specific File Not Found exception, that is much easier to recover from. You can tell the user definitively that the file doesn't exist.
I don't see a reason to believe that custom exceptions are any more expensive than the built-in ones.
"Expensive" is a relative term and - as the name already suggests - an exception should be an exception, so it will probably not affect the performance of your code. The cost of throwing an exception is - as far as I know - independent of the type of the exception, so you should not restrict yourself to System.Exception.
But most important: http://c2.com/cgi/wiki?PrematureOptimization
I prefer to use the most appropriate built in exception, and if that doesn't already exist, derive my own from System.ApplicationException.
I wouldn't recommend throwing System.Exception with a custom message.
Your coworker is talking nonsense. Throwing an exception is the same cost regardless of the class.
And to be honest, all this talk of "expensive" exceptions - yes they are more expensive than a null check or some such, so don't ever use them as a replacement for some sanity check, but they should be encouraged where they make sense (like IOException for example, that's an excellent use case for them - problems with I/O are an exceptional case and they usually must be handled outside of normal program flow).
I'm tasked with writing an Exception Handling Strategy and Guidelines document for a .NET/C# project I'm working on. I'm having a tough go at it. There's plenty of information available for how/when to throw, catch, wrap exceptions, but I'm looking for describing what sorts of things should go on inside the catch block short of wrapping and throwing the exception.
try
{
DoSomethingNotNice();
}
catch (ExceptionICanHandle ex)
{
//Looking for examples of what people are doing in catch blocks
//other than throw or wrapping the exception, and throwing.
}
Thanks in advance
It means exactly that. If you are expecting code you're running to throw an exception, and when that exception is thrown your code knows what went wrong and how to proceed, then catch the exception and handle it.
Basically, the rule exists to prevent anti-patterns like:
try
{
...
}
catch(Exception ex)
{
throw;
}
The catch here does nothing but add a speed bump to unwinding the call stack. If you don't actually want to do anything with the exception you're catching, you shouldn't even bother with the catch.
A related but far more valid case is where you don't care about the exception being thrown, but you need to clean up in all cases. In that case, skip the catch; you don't need it, just make it a try-finally block.
EDIT: To answer the question in the post, not just the subject, you could write a rule as follows: "Do not code a try-catch statement that does not do anything, or only rethrows the caught exception. All catch statements should perform some value-added action relating to the thrown exception."
For example, let's say you are trying to connect to a SQL Server instance using credentials supplied by the user when they log into your app. Dozens of things could go wrong, some of which you can't expect, some of which you should.
Server isn't responding - you can try again; perhaps call the connection method recursively in the catch, with a "retry counter" to break the otherwise infinite loop.
User failed authentication - show a friendly (or not-so-friendly, but concise and understandable) message in red on the dialog box.
User not authorized to connect to the specified DB - Depends on your security setup; in most offices, that's something you should e-mail the DBA about because it means he created the login but forgot to assign the proper rights.
Network not available: You can alert the user through an error on the login dialog or a new dialog, retry a couple of times, etc.
Division by zero - WTF? What could possibly cause a Div by Zero during a login? You're not expecting this exception, you have no clue what went wrong in this case and therefore can't continue running code, so don't catch it.
If anything goes wrong, you may want to log the message to a file or a shared resource for audit/security purposes. This should happen at lower levels if you want to continue execution, or higher levels if you're going to gracefully shut down afterward.
All of these examples involve first catching the exception of a known type and interrogating it to see what exactly went wrong, then performing some known action that can allow the program to continue execution. The object is to prevent the application from crashing and burning when something goes wrong that you know could go wrong, but know how to keep the program running in that case.
The basic rules for catching exceptions:
If you aren't expecting an exception, don't catch one.
If you can't or don't want to continue execution of code after receiving an exception, whether you know it can happen or not, don't catch it.
If you are expecting the exception to occur, and know-how to continue executing code when it happens (at least for a while), then catch and perform any special actions you need in order to do so.
NEVER trap exceptions (an empty catch block); that causes applications to fail silently in even more unpredictable ways.
NEVER leave catch-and-rethrow (a catch block with only a rethrow) in production code. They can sometimes be useful when debugging as they allow you to identify specific segments of code that are failing, but in production code, they're just a speed bump to throwing out or actually dealing with the exception.
I think the basic idea underlying this common piece of advice is to avoid scenarios like this:
try
{
SomeImportantResource = GetSomeImportantResource();
SomeOtherImportantResource = GetSomeOtherImportantResource();
}
catch (Exception ex)
{
SomeGlobalErrorHandlingMechanism(ex);
}
I've worked with developers who, when confronted with a bug, would simply wrap the offending code in a try/catch block and say, "I fixed the bug." The problem in scenarios like the above example is that by simply catching an exception and not fixing the problem that caused it, you're liable to undermine the solidity of your program. Above, what the catch has done is made us uncertain whether SomeImportantResource and SomeOtherImportantResource were ever initialized properly. It seems likely that there could be code elsewhere in the program that requires for these to be initialized, in which case, we've just introduced a bug by "fixing" a bug.
So I think the standard wisdom is to only try to deal with an exception if you can recover from it in such a way that it does not compromise any other code elsewhere in your program.
Or, better than that: don't catch the exception and make some feeble attempt (or non-attempt) to "handle" it; figure out what caused it and fix that problem. Obviously this is not always possible, but it is possible a lot more often than it should be.
Consider if you had an application like OneNote that lets you store your files on a shared network drive, but in the event the network is unavailable, then it uses local storage temporarily until the main storage is available.
If your program got an exception while interacting with the files, then you could retry the action with the local storage.
This is an example where you have a specific program behavior you want, and accomplish it by how you handle the exception. Generally, you should try to find a way to accomplish your goal without using exception handling, such as in the above exmple, you could always check to see if the file is available before attempting to operate on it. That way you can just code it as an "if/else" instead of a "try/catch". However, if you did that, there is still always the chance in the above case that someone may lose access to a file in the middle of an operation, such that regardless of whether you checked in advance, you still might get an exception that you can handle gracefully. So you'd probably refactor your else block into a function that is both called from the else and the catch, so that you can gracefully fallback to local storage in either case.
I also often include logging if there is no security issue with what I'm logging, and a rethrow as you mentioned, and my logging includes more descriptive information and context information, maybe some local values, which make debugging easier. I always strive to have log files so detailed that I can determine the cause of a problem without having to reproduce on my machine. I hate hearing programmers make the "I can't reproduce it" excuse. You don't have to reproduce it. If your logging is adequate then there is no need to reproduce it.
When an exception trickles up via rethrow's all the way to your GUI layer, then at that point is where you catch it and do not rethrow it, but instead display a message to the user indicating that an unexpected error occurred, and usually exit the application. You might give them an opportunity to save work, but maybe automatically making a backup of the file being overwritten, as an unhandled exception is something you never coded for, meaning something might be corrupt, and you might be saving a bad file, yet leading the user to believe they are saving their work. This is ultimately the reason many program opt to kill themselves if something unexpected occurs, as from that point on who knows what state the program might be in, and something as simple as saving some rows in a database might have serious consequences and hose alot of data.
If you can perform an action when you catch an exception that is helpful in some way (such as executing a block of code that will perform the function attempted in the try statement, but does it in a different, but perhaps less efficient way, or simply informing the user that their action couldn't be performed), then you should catch it and do so. If you are simply logging the exception to track down the problem later, then you should rethrow the exception throw; (NOT throw ex;), in case there is another block of code that can handle that type of exception.
It's also acceptable to catch an exception to wrap the caught exception in your own exception that may make more sense to the calling function.
Some examples:
Log the exception and just carry on
Retry the thing that went wrong
Try another method of doing what you were trying to do
It all depends on what went wrong. The point is, just catching and re-throwing is of no use to anyone.
If your code can gracefully handle a specific type of exception, catch it and handle it, and then let your code keep going. If not, let the exception propagate up, because it may be caught at a higher level or it may be something really wrong that you shouldn't be catching as it might mask the error.
You shouldn't catch an exception you can't handle, but you can catch exceptions that you might be able to handle:
try
{
DoSomethingNotNice();
}
catch (ExceptionIMightBeAbleToHandle ex)
{
if(iCanHandle(ex))
thenHandle(ex);
else
throw;
}
Note that using throw by itself is supposed to preserve stack trace info.
Typical things you can handle gracefully would be a FileNotFoundException.
The catch block should teardown anything that may have been opened for use in the try and due to the exception being thrown not closed down properly. Database connections and file access are the ones that usually need closing down (though proper use of a using block can handle this)
Once that has been done you can use throw; to chuck the exception up to the next level
Alternatively you might want to wrap your current exception inside a new exception more relevant to the current method
catch(LowLevelException ex){
throw new HighLevelException("argh bad things happened!",ex);
}
Coming late to the game but the MS recommended way to handle errors globally in .net core is middleware.
Also you can use a switch statement like this to make sure you re-throw errors you can't handle.
Trying to keep my answer as general as the question ;) but I can provide some code if needed.
I've dealt with instances where I would throw/rethrow an exception knowing that the code surrounding it would catch the specific exception. But is there any time you would want to throw an exception, knowing that it wouldn't be caught?
Or at least, NOT catch an exception?
Exceptions immediately halt the application unless their handled right? So I guess I'm asking if you would ever want to purposely let your application die?
If your application is primarily going to be used by other clients and is not standalone, it generally makes sense to throw exceptions if a condition arises that you don't know how to (or don't want to) handle, and there's no sensible way for you to recover from it. Clients should be able to decide how they want to handle any exceptions that you might throw.
On the other hand, if your application is the endpoint, throwing an exception essentially becomes a notification mechanism to alert people that something has gone terribly wrong. In such cases, you need to consider a few things:
How important is the continued running of the application? Is this error really unrecoverable? Throwing an exception and terminating your program is not something you want to be doing on the space shuttle.
Are you using exceptions as a proxy for real logging? There's almost never a reason to do this; consider a real logging mechanism instead. Catch the exception and have the logger work out what happened.
What are you trying to convey by throwing the exception yourself? Ask yourself what the value in throwing a new exception is, and consider carefully whether there isn't a better way to do what you want.
Not catching an exception may leave resources in a bad state. If you don't gracefully exit, things are generally not cleaned up for you. Make sure you understand what you're doing if you need to do this -- and if you're not going to catch it, at least consider a try-finally block so you can do some tidying up.
There's a very good rule that I came across a while ago:
Throw an exception when a method can't do what its name says it does.
The idea is that an exception indicates that something has gone wrong. When you are implementing a method, it is not your responsibility to be aware of whether it will be used correctly or not. Whether the code using your method catches the exception or not is not your responsibility, but the responsibility of the person using your method.
Another rule to follow is:
Don't catch an exception unless you know what you want to do with it.
Obviously, you should include cleanup code in a try...finally block, but you should never just catch an exception just for the sake of catching it. And you should never swallow exceptions silently. While there are occasions when you may want to catch all exceptions (e.g. by doing catch (Exception ex) in C#), these are fairly uncommon and generally have a very specific technical reason. For example, when you are using threads in .NET 2.0 or later, if an exception escapes from your thread, it will cause the entire application domain to unload. In these cases, however, at the very minimum you should log the exception details as an error and provide an explanation in the comments.
Sure. For example, if you're trying to load some bytes into a string in Java:
try {
String myString = new String(byteArray, "UTF-8");
} catch (UnsupportedEncodingException e) {
// Platform doesn't support UTF-8? What is this, 1991?
throw new RuntimeExceptione(e);
}
In this case, there is no graceful degradation, the platform simply can't support the operation desired. You can check for this condition at initialization all you want, but the constructor for String still throws this exception, and you have to deal with it. Either that, or use Charset.forName() :)
Generally, and certainly in early iterations of your application, don't catch the exception. More often than not, the recovery from an exception will require a business rule of some sort, and, more often than not, those business rules are not defined for you. If you "handle" the exception instead of letting the application die then you will most likely be inventing business rules for your customer. Not good.
The general pattern of catching every exception just for the sake of catching it has caused me more headaches than I can count. It usually happens that someone puts some sort of generic exception handling code throughout the application, which inevitably ends up hiding a bug or creating some behavior that is unwanted. (incidentally, catching and then not rethrowing is even worse.)
So, I'd suggest that you ask instead: "When should I catch an exception?"
Here's the thing ... it is about "layers", or "encapsulation", or "low coupling". At some place in your codebase, you're writing a method to do something. Say it's a public method. Therefore, it should not assume much or anything about the caller ... rather, it should merely do the job it is supposed to do, regardless of who is calling it and what context the caller is in.
And if, for some reason, it cannot complete its job, then it needs to tell the caller "Sorry, I couldn't do that, and here's why". Exceptions are an excellent mechanism to let it tell the caller that (not the only mechanism, but the best mechanism I've ever seen for most cases).
So, when you throw the exception, you have no idea whether it will be caught or not ... because you're exposing a public method and you have no idea who might choose to call it and why.
The catching of the exception is the job of the "context". For example, say you're writing a library with public methods that might throw exceptions. Then, say you're using that library from a Windows Forms app. The Windows Forms app might catch exceptions and show a message box to the user.
But later, you might use the same library from a Windows Service. The Service would be more likely to catch the exception, log it, return an error to the original caller, but keep running so it can process further requests.
So the exception is like a contractual agreement between the caller and the provider. The provider says, "I'll either do the job or tell you why I can't. What you do from there is your own business." And the caller says, "OK, if you can't do the job, just tell me why, and I'll decide what to do in that case."
But is there any time you would want to throw an exception, knowing that it wouldn't be caught?
I would say that if you're manually throwing an exception, most of the time you don't know if it will be caught. If you knew it would be caught you could just handle it yourself rather than throwing the exception in the first place.
To be fair, I suppose that depends in part on the kind of programming you're doing, and sometimes the same programmer ends up building both the library and the code that consumes said library.
Would you ever NOT catch an exception?
If you didn't expect/weren't aware an exception could be thrown. But putting that aside and assuming you are aware of the exception, sometimes you know about it at one tier but know the next tier up is the more appropriate place to handle it.
It depends on the type of application. Web applications can continue running even after exceptions have bubbled up to the execution context.
It is common practice to 'throw/rethrow' an exception if you catch the exception at a level where it can't be dealt with. But, you would almost always add context to the issue, at the very least add some logging at the higher level to say that it was caught and rethrown.
for example
A calls B calls C (throws exception)
B catches/rethrows
A catches.
In this case, you would want B to add some logging so that you can differentiate between B generating and throwing an error, and C generating and throwing an error. That would allow you a greater ability to debug and fix problems later.
In general you will almost NEVER want an exception to kill your program. The best practice is to catch the except and exit gracefully. This allows you to save any currently open information and release resources that are being used so they don't become corrupted. If you intend to exit, you can create your own 'core-dump' information report that includes the things you were doing when you caught the fatal exception.
If you let the exception kill your process you are eliminating your chance to get custom tailored crash information, and you are also skipping the part where you provide the user with a friendly error message and then exit.
So, I would recommend ALWAYS catching exceptions, and never voluntarily letting them run amok in your program.
EDIT
If you are writing a library, you have to choose ahead of time whether your function will throw an exception, or be exception safe. In those cases, sometimes you will throw an exception and have no idea if the calling party will catch it. But in that case, catching it is not your responsibility, as long as the api declares that the function could throw exceptions.
(I'm looking for a word that means 'could possibly throw exception'... anyone know what it is? It's going to bug me all day.)
Firstly, there absolutely are situations where it is better to not catch an exception.
Sometimes, an exception can sometimes tell you that your program is in an unknown state. There are a number of exceptions where this is pretty much intrinsically true given the exception type. A NullReferenceException essentially tells you "there is a bug". And by catching such an exception, you may hide the bug, which sounds good in the short term, but in the long term you'd be happier to fix it. The product may not crash, but it certainly won't have the expected behaviour.
But this is also true for exception types we invent for ourselves. Sometimes, the fact that exception A has been thrown should be "impossible" - and yet it has happened, so there's a bug.
Also, something very important happens when you catch an exception: the finally blocks for the whole call stack inside the try block (and anything it calls) will be executed. What do those finally blocks do? Well, anything. And if the program is in an unknown state, I really do mean anything. They could erase valuable customer data from the disk. They could throw more exceptions. They could corrupt data in memory, making the bug impossible to diagnose.
So when an exception indicates an unknown state, you don't want to run any more code, so whatever you do, don't catch the exception. Let it fly past, and your program will terminate harmlessly, and Windows Error Reporting will be able to capture the state of the program as it was when the problem was originally detected. If you catch the exception, you will cause more code to execute, which will screw up the state of the program further.
Secondly, should you throw an exception knowing it won't be caught? I think that question misunderstands the nature of reusable methods. The whole idea of a method is that it has a "contract" that it follows: it accepts certain parameters and returns a certain value, plus also it throws certain exceptions under certain conditions. That's the contract - it's up to the caller what they do with it. For some callers, exception A might indicate a recoverable condition. For other callers, it might indicate a bug. And from what I said above, it should be clear that if an exception indicates a bug, it must not be caught.
And if you're wondering what this means for the Microsoft Enterprise Library's Exception Handling Block: yes, it's pretty broken. They tell you to catch (Exception x) and then decide whether to rethrow based on your policy; too late - the finally blocks have already executed by that point. Don't do that.
You probably wouldn't want an uncaught exception anywhere where the end-users can see it, but it is often acceptable to let clients of your API (other programmers) decide how to handle exceptions.
For example, suppose you are designing a Java class library. You expose a public method that takes in a String. In your application, a null input value would cause an error. Instead of handling the error yourself, it would be acceptable to check for a null value, then throw an IllegalArgumentException.
You must, of course, document that your method throws this exception in this circumstance. This behavior becomes part of your method's contract.
It depends on what you mean by 'being caught'. Something, somewhere eventually catches the exception whether it be the underlying OS or something else.
We have a workflow system that executes job plans comprised of individual jobs. Each job runs a unit of code. For some of the exceptions, we don't want to handle them in the code but throw it up the stack so that the external workflow system catches it (which happens completely outside of the thrower's process).
If you're writing the entire application, then your reasons are your own. I can think of a few situations where you might want to throw the exception and let the app die, most of them are not very good reasons though.
The best reason is usually when debugging. I frequently disable exceptions while debugging to allow me to know better where something is failing. You can also just turn on thrown exception breaks in the debugger if you're running it on a machine with the debugger.
Another possible reason is when continuing after an exception is thrown doesn't make sense or would result in possible irrecoverable data corruption or worse (think Robots with laser beams, but then you should be damn sure your applicaiton deals with these situations IMO, crashing the program is just the lazy way).
If you're writing API code, or Framework code that you won't use yourself, then you have no idea if someone will catch your exceptions.
Yup, it's my ONLY opportunity to slap the developer consuming the service/object to tell them "Ur dO1n it WrOnG!!!!".
That and getting rid of possibilities that you don't want to permit or are seemingly "impossible". Apps that catch all exceptions and continue are just a walled garden surrounded by chaos.
If I need a moderately large system that is somehow processing data in what I believe to be a consistent manner.
And
Somewhere along the line, I detect that the application's state has become inconsistent.
And
The system doesn't (yet) know how to fix the inconsistency and recover gracefully
Then, yes, I would throw an exception with as much detail as possible and cause the application to die as quickly as possible, to avoid doing any further harm to the data. If it can be recovered, it'd be important not to exacerbate the problem by trying feebly to cover up the mess.
Later along the line, once the chain of events that led to the inconsistency is better understood, I higher facility can catch that exception, repair the state, and continue with minimal interruption.
A library will often throw exceptions based on defensive programming checks, should a condition arise that shouldn't have been allowed to arise by the application code. Applications code will often be written such that most of those invalid conditions will never arise, and therefore the exceptions will never be thrown, so there's no point catching them.
Depending on language (I'm mostly thinking in terms of C++ rather than C#, and not that clear what the differences are) the effect of an uncaught exception actually being thrown is probably the same as what used to be done in the days before exceptions were invented. A common policy for defensive programming in C libraries, for example, was to terminate the program immediately with an error message.
The difference is that if the exception throw does turn out to be possible (hopefully this will be discovered through unit testing), it is often relatively easy to add an exception handler that can recover from the problem in a more constructive way. You don't have to rewrite the library, or add complex checks in application code to ensure the condition cannot arise before the exception-throwing call is made.
I have quite a few exception throws that are never caught. They are all for defensive purposes, and while being uncaught is bad for an exception that does happen, this only ever happens during development and testing, for error conditions I failed to consider in the application code so far. And when it happens, it is unusual for the fix to be awkward - no need for a large-scale refactoring, no need for the applications code to be massively complicated with error condition checks, just a catch clause with a relatively simple recovery or "I'm sorry, Dave, I'm afraid I can't do that." without failing out the whole app.
I keep hearing that
catch (Exception ex)
Is bad practise, however, I often use it in event handlers where an operation may for example go to network, allowing the possibility of many different types of failure. In this case, I catch all exceptions and display the error message to the user in a message box.
Is this considered bad practise? There's nothing more I can do with the exception: I don't want it to halt the application, the user needs to know what happened, and I'm at the top level of my code. What else should I be doing?
EDIT:
People are saying that I should look through the stack of calls and handle errors specifically, because for example a StackOverflow exception cannot be handled meaningfully. However, halting the process is the worst outcome, I want to prevent that at all costs. If I can't handle a StackOverflow, so be it - the outcome will be no worse than not catching exceptions at all, and in 99% of cases, informing the user is the least bad option as far as I'm concerned.
Also, despite my best efforts to work out all of the possible exceptions that can be thrown, in a large code-base it's likely that I would miss some. And for most of them the best defense is still to inform the user.
The bad practice is
catch (Exception ex){}
and variants:
catch (Exception ex){ return false; }
etc.
Catching all exceptions on the top-level and passing them on to the user (by either logging them or displaying them in a message-box, depending on whether you are writing a server- or a client-application), is exactly the right thing to do.
I find the arguments that generic catches are always bad to be overly dogmatic. They, like everything else, have a place.
That place is not your library code, nor the classes you custom-develop for your app. That place is, as many have mentioned, the very top level of the app, where if any exception is raised, it is most likely unexpected.
Here's my general rule (and like all rules, it's designed to be broken when appropriate):
I use classes and custom-built libraries for the majority of the lifting in an app. This is basic app architecture -- really basic, mind you. These guys try to handle as many exceptions as possible, and if they really can't continue, throw the most specific kind available back up to the UI.
At the UI, I tend to always catch all from event handlers. If there is a reasonable expectation of catching a specific exception, and I can do something about it, then I catch the specific exception and handle it gracefully. This must come before the catch all, however, as .NET will only use the very first exception handler which matches your exception. (Always order from most specific to most generic!)
If I can't do anything about the exception other than error out (say, the database is offline), or if the exception truly is unexpected, catch all will take it, log it, and fail safe quickly, with a general error message displayed to the user before dying. (Of course, there are certain classes of errors which will almost always fail ungracefully -- OutOfMemory, StackOverflow, etc. I'm fortunate enough to have not had to deal with those in prod-level code ... so far!)
Catch all has its place. That place is not to hide the exception, that place is not to try and recover (because if you don't know what you caught, how can you possibly recover), that place is not to prevent errors from showing to the user while allowing your app to continue executing in an unknown and bad state.
Catch all's place is to be a last resort, a trap to ensure that if anything makes it through your well-designed and well-guarded defenses, that at a minimum it's logged appropriately and a clean exit can be made. It is bad practice if you don't have well-designed and well-guarded defenses in place at lower levels, and it is very bad practice at lower levels, but done as a last resort it is (in my mind) not only acceptable, but often the right thing to do.
When I see
catch (Exception ex)
my hand starts to groping for a hammer. There are almost no excuses to catch base Exception. Only valid cases that come to my mind are:
1) 3rd party component throws Exception (be damned it's author)
2) Very top level exceptions handling (as a last resort) (for example handle "unhandled" exceptions in WinForms app)
If you find a case where many different types of exceptions can happen it's a good sign of bad design.
I would disagree with Armin Ronacher. How would you behave if StackOverflow exception raised? Trying to perform additional actions can lead to even worse consequences. Catch exception only if you can handle it in meaningful and safe way. Catching System.Exception to cover range of possible exceptions is terribly wrong. Even when you are re-throwing it.
It makes complete sense to catch the exception at the highest level in your code. Catching the base Exception type is fine as long as you don't need to do any different logic based on the exception's type.
Also, make sure you're displaying a friendly, general error message and not showing the actual exception's message. That may lead to security vulnerabilities.
Yes, it is fine to catch the base Execption at the top level of the application, which is what you are doing.
The strong reactions you are getting is probably because at any other level, its almost always wrong to catch the Base exception. Specifically in an a library it would be very bad practice.
It is bad practice in the sense that you shouldn't do it everywhere.
In this case, I would consider it the only reasonable solution as your exception could be truly anything. The only possible improvement would be to add extra handlers before your catch everything for specific error cases where you could do something about the exception.
It's perfectly okay if you re-raise exceptions you can't handle properly. If you just catch the exceptions you could hide bugs in the code you don't expect. If you catch exceptions to display them (and bypass the die-and-print-traceback-to-stderr behavior) that's perfectly acceptable.
I think the poster is referring to exception handling like this:
try {something} catch (SqlException) {do stuff} catch (Exception) {do other stuff}
The idea here is that you want to catch the more specific errors (like SqlException) first and handle them appropriately, rather than always relying on the catch-all general Exception.
The conventional wisdom says that this is the proper way to do exception handling (and that a solo Catch (Exception ex) is bad). In practice this approach doesn't always work, especially when you're working with components and libraries written by someone else.
These components will often throw a different type of exception in production than the one your code was expecting based on how the component behaved in your development environment, even though the underlying problem is the same in both environments. This is an amazingly common problem in ASP.NET, and has often led me to use a naked Catch (Exception ex) block, which doesn't care what type of exception is thrown.
Structured exception handling is a great idea in theory. In practice, it can still be a great idea within the code domain that you control. Once you introduce third party stuff, it sometimes doesn't work very well.
We use Catch ex as Exception (VB.Net variant) quite a bit. We log it, and examine our logs regularly. Track down the causes, and resolve.
I think Catch ex as Exception is completely acceptabile once you are dealing with production code, AND you have a general way to handle unknown exceptions gracefully. Personally I don't put the generic catch in until I've completed a module / new functionality and put in specialized handling for any exceptions I found in testing. That seems to be the best of both worlds.
No; in that case if you don't want to halt the program there's nothing else you can do and at the top level is the right place to do it, as long as you're logging properly and not hiding it away in hope grin
The important thing is to understand the path of exceptions through your application, and not just throw or catch them arbitrarily. For example, what if the exception you catch is Out-Of-Memory? Are you sure that your dialog box is going to display in that case? But it is certainly fine to define a last-ditch exception point and say that you never want errors to propagate past that point.
You should catch the exceptions related to what you are doing. If you look at the methods you call, you will see what exceptions they throw, and you want to stay more specific to those. You should have access to know what exceptions may be thrown by the methods you call, and handle them appropriately.
And... better than having one big try catch, do your try and catch where you need the catch.
try {
myThing.DoStuff();
}
catch (StuffGoneWrongException ex) {
//figure out what you need to do or bail
}
Maybe not quite this closely packed, but it depends on what you are doing. Remember, the job isn't just to compile it and put it on someones desktop, you want to know what breaks if something did and how to fix it. (Insert rant about tracing here)
a lot of times exception are catched to free resources, it' s not important if exception is (re)thrown. in these cases you can avoid try catch:
1) for Disposable object you can use "using" keyword:
using(SqlConnection conn = new SqlConnection(connStr))
{
//code
}
once you are out of the using scope (normally or by a return statement or by exception), Dispsose method is automatically called on object. in other word, it' s like try/finally construct.
2) in asp.net, you can intercept Error or UnLoad event of Page object to free your resource.
i hope i help you!
I'm responding to "However, halting the process is the worst outcome..."
If you can handle an exception by running different code (using try/catch as control flow), retrying, waiting and retrying, retrying with an different but equivalent technique (ie fallback method) then by all means do so.
It is also nice to do error message replacement and logging, unless it is that pseudo-polite-passive-aggressive "contact your administrator" (when you know there is no administrator and if there was the administrator can't do anything about it!) But after you do that, the application should end, i.e. same behavior you get with an unhandled exception.
On the other hand, if you intend to handle the exception by returning the user to a code thread that has potentially trashed its state, I'd say that is worse than ending the application and letting the user start over. Is it better for the user to have to restart at the beginning or better to let the user destroy data?
If I get an unexpected exception in the module that determines which accounts I can withdraw money from, do I really want to log and report an Exception and return the user to the withdraw money screen? For all we know we just granted him the right to withdraw money from all accounts!
This is all good of catching exceptions that you can handled. But sometimes it also happens that due to unstable environment or users just do the process correctly, the application runs into unexpected exception. Which you haven't been listed or handled in code. Is there a way that the unhandled exception is captured from app.config file and displays a common error?
Also puts that details exception message in a log file.
I've been working a fair bit with exceptions, and here's the implementation structure I'm currently following:
Dim everything to Nothing / String.Empty / 0 etc. outside of Try / Catch.
Initialise everything inside Try / Catch to desired values.
Catch the most specific exceptions first, e.g. FormatException but leave in base Exception handling as a last resort (you can have multiple catch blocks, remember)
Almost always Throw exceptions
Let Application_Error sub in global.asax handle errors gracefully, e.g. call a custom function to log the details of the error to a file and redirect to some error page
Kill all objects you Dim'd in a Finally block
One example where I thought it was acceptable to not process an exception 'properly' recently was working with a GUID string (strGuid) passed via HTTP GET to a page. I could have implemented a function to check the GUID string for validity before calling New Guid(strGuid), but it seemed fairly reasonable to:
Dim myGuid As Guid = Nothing
Try
myGuid = New Guid(strGuid)
'Some processing here...
Catch ex As FormatException
lblError.Text = "Invalid ID"
Catch ex As Exception
Throw
Finally
If myGuid IsNot Nothing Then
myGuid = Nothing
End If
End Try