I have been programming for the last 3 years. When I program, I use to handle all known exceptions and alert the user gracefully. I have seen some code recently which has almost all methods wrapped inside try/catch blocks. The author says it is part of defensive programming. I wonder, is this really defensive programming? Do you recommend putting all your code in try blocks?
My basic rule is : Unless you can fix the problem which caused the exception, do not catch it, let it bubble up to a level where it can be dealt with.
In my experience, 95% of all catch blocks either just ignore the exception (catch {}) or merely log the error and rethrow the exception. The latter might seem like the right thing to do, but in practice, when this is done at every level, you merely end up with your log cluttered with five copies of the same error message. Usually these apps have an "ignore catch" at the top most level (since "we have try/catch at all the lower levels"), resulting in a very slow app with lots of missed exceptions, and an error log that too long for anyone to be willing to look through it.
Extensive use of Try...Catch isn't defensive programming, it's just nailing the corpse in an upright position.
Try...Finally can be used extensively for recovery in the face of unexpected exceptions. Only if you expect an exception and now how to deal with it should you use Try..Catch instead.
Sometimes I see Try..Catch System.Exception, where the catch block just logs the exception and re-throws. There are at least 3 problems with that approach:
Rethrow assumes an unhandled exception, and therefore that the program should terminate because it's in an unknown state. But catch causes the Finally blocks below the Catch block to run. In an undefined situation, the code in these Finally blocks could make the problem worse.
The code in those Finally blocks will change program state. So any logging won't capture the actual program state when the exception was originally thrown. And investigation will be more difficult because the state has changed.
It gives you a miserable debugging experience, because the debugger stops on the rethrow, not the original throw.
No, it's not "defensive programming." Your coworker is trying to rationalize his bad habit by employing a buzzword for a good habit.
What he's doing should be called "sweeping it under the rug." It's like uniformly (void)-ing the error-status return value from method calls.
The term "defensive programming" stands for writing code in such a way that it can recover from error situations or that it avoid the error situation altogether. For example:
private String name;
public void setName(String name) {
}
How do you handle name == null? Do you throw an exception or do you accept it? If it doesn't make sense to have an object without a name, then you should throw an exception. What about name == ""?
But ... later you write an editor. While you set up the UI, you find that there are situations where a user can decide to take the name away or the name can become empty while the user edits it.
Another example:
public boolean isXXX (String s) {
}
Here, the defensive strategy is often to return false when s == null (avoid NPEs when you can).
Or:
public String getName() {
}
A defensive programmer might return "" if name == null to avoid NPEs in calling code.
If you're going to handle random exceptions, handle them in only one place - the very top of the application, for the purposes of:
presenting a friendly message to the user, and
saving the diagnostics.
For everything else, you want the most immediate, location-specific crash possible, so that you catch these things as early as possible - otherwise exception handling becomes a way of hiding sloppy design and code.
In most cases where the exception is predictable, it's possible to test ahead of time, for the condition that the exception handler will catch.
In general, If...Else is much better than Try...Catch.
Catching random exceptions is bad. What then?
Ignore them? Excellent. Let me know how that works for them.
Log them and keep running? I think not.
Throw a different exception as part of crashing? Good luck debugging that.
Catching exceptions for which you can actually do something meaningful is good. These cases are easy to identify and maintain.
Can I just say as an aside here that every time one of my co-workers writes a method signature with "throws Exception" instead of listing the types of exceptions the method really throws, I want to go over and shoot them in the head? The problem is that after a while you've got 14 levels of calls all of which say "throws Exception", so refactoring to make them declare what they really throw is a major exercise.
There is such a thing as "too much" processing, and catching all exceptions kindof defeats the point. Specifically for C++, the catch(...) statement does catch all exceptions but you can't process the contents of that exception because you don't know the type of the exception (and it could be anything).
You should catch the exceptions you can handle fully or partially, rethrowing the partial exceptions. You should not catch any exceptions that you can't handle, because that will just obfuscate errors that may (or rather, will) bite you later on.
I would recommend against this practice. Putting code into try-catch blocks when you know the types of exceptions that can be thrown is one thing. It allows you, as you stated, to gracefully recover and/or alert the user as to the error. However, putting all your code inside such blocks where you don't know what the error is that may occur is using exceptions to control program flow, which is a big no-no.
If you are writing well-structured code, you will know about every exception that can occur, and can catch those specifically. If you don't know how a particular exception can be thrown, then don't catch it, just-in-case. When it happens, you can then figure out the exception, what caused it, and then catch it.
I guess the real answer is "It depends". If try-catch blocks are catching very generic exceptions then I would say it is defensive programming in the same way that never driving out of your neighborhood is defensive driving. A try-catch (imo) should be tailored to specific exceptions.
Again, this is just my opinion, but my concept of defensive programming is that you need fewer/smaller try-catch blocks not more/larger ones. Your code should be doing everything it can to make sure an exception condition can never exist in the first place.
In C++ the one reason to write lots of try/catch blocks is to get a stack trace of where the exception was thrown. What you do is write a try/catch everywhere, and (assuming you aren't at the right spot to deal with the exception) have the catch log some trace info then re-throw the exception. In this way, if an exception bubbles all the way up and causes the program to terminate, you'll have a full stack trace of where it all started to go wrong (if you don't do this, then an unhandled C++ exception will have helpfully unwound the stack and eradicated any possibility of you figuring out where it came from).
I would imagine that in any language with better exception handling (i.e. uncaught exceptions tell you where they came from) you'd want to only catch exceptions if you could do something about them. Otherwise, you're just making your program hard to read.
I've found "try" "catch" blocks to be very useful, especially if anything realtime (such as accessing a database) is used.
Too many? Eye of the beholder.
I've found that copying a log to Word, and searching with "find" -- if the log reader does not have "find" or "search" as part of its included tools -- is a simple but excellent way to slog through verbose logs.
It certainly seems "defensive" in the ordinary sense of the word.
I've found, through experience, to follow whatever your manager, team-leader, or co-worker does. If you're just programming for yourself, use them until the code is "stable" or in debug builds, and then remove them when done.
Related
Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
Obviously this is one of those questions where the only real answer is "it depends."
The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.
The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.
The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:
try {
something();
} catch (Exception ex) {}
or this in Python:
try:
something()
except:
pass
Because these can be some of the hardest issues to track down.
A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
Unless you are doing some logging and clean up code in the front end of your application, then I think it is bad to catch all exceptions.
My basic rule of thumb is to catch all the exceptions you expect and anything else is a bug.
If you catch everything and continue on, it's a bit like putting a sticking plaster over the warning light on your car dashboard. You can't see it anymore, but it doesn't mean everything is ok.
Yes! (except at the "top" of your application)
By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem. You are stating that this is a recoverable situation. Catching Exception or SystemException means that you will catch problems like IO errors, network errors, out-of-memory errors, missing-code errors, null-pointer-dereferencing and the likes. It is a lie to say that you can deal with these.
In a well organised application, these unrecoverable problems should be handled high up the stack.
In addition, as code evolves, you don't want your function to catch a new exception that is added in the future to a called method.
In my opinion you should catch all exceptions you expect, but this rule applies to anything but your interface logic. All the way down the call stack you should probably create a way to catch all exceptions, do some logging/give user feedback and, if needed and possible, shut down gracefully.
Nothing is worse than an application crashing with some user unfriendly stacktrace dumped to the screen. Not only does it give (perhaps unwanted) insight into your code, but it also confuses your end-user, and sometimes even scares them away to a competing application.
There's been a lot of philosophical discussions (more like arguments) about this issue. Personally, I believe the worst thing you can do is swallow exceptions. The next worst is allowing an exception to bubble up to the surface where the user gets a nasty screen full of technical mumbo-jumbo.
Well, I don't see any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.
In conclusion, you will catch both IOException and NullPointerException with a generic Exception, but the way your program should react is probably different.
The point is twofold I think.
Firstly, if you don't know what exception has occurred how can you hope to recover from it. If you expect that a user might type a filename in wrong then you can expect a FileNotFoundException and tell the user to try again. If that same code generated a NullReferenceException and you simply told the user to try again they wouldn't know what had happened.
Secondly, the FxCop guidelines do focus on Library/Framework code - not all their rules are designed to be applicable to EXE's or ASP.Net web sites. So having a global exception handler that will log all exceptions and exit the application nicely is a good thing to have.
The problem with catching all exceptions is that you may be catching ones that you don't expect, or indeed ones that you should not be catching. The fact is that an exception of any kind indicates that something has gone wrong, and you have to sort it out before continuing otherwise you may end up with data integrity problems and other bugs that are not so easy to track down.
To give one example, in one project I implemented an exception type called CriticalException. This indicates an error condition that requires intervention by the developers and/or administrative staff otherwise customers get incorrectly billed, or other data integrity problems might result. It can also be used in other similar cases when merely logging the exception is not sufficient, and an e-mail alert needs to be sent out.
Another developer who didn't properly understand the concept of exceptions then wrapped some code that could potentially throw this exception in a generic try...catch block which discarded all exceptions. Fortunately, I spotted it, but it could have resulted in serious problems, especially since the "very uncommon" corner case that it was supposed to catch turned out to be a lot more common than I anticipated.
So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead.
A similar rule here is never throw exceptions of type System.Exception. You (or another developer) may want to catch your specific exception higher up the call stack while letting others go through.
(There is one point to note, however. In .NET 2.0, if a thread encounters any uncaught exceptions it unloads your whole app domain. So you should wrap the main body of a thread in a generic try...catch block and pass any exceptions caught there to your global exception handling code.)
I would like to play devil's advocate for catching Exception and logging it and rethrowing it. This can be necessary if, for example, you are somewhere in the code and an unexpected exception happens, you can catch it, log meaningful state information that wouldn't be available in a simple stack trace, and then rethrow it to upper layers to deal with.
There are two completely different use cases. The first is the one most people are thinking about, putting a try/catch around some operation that requires a checked exception. This should not be a catch-all by any means.
The second, however, is to stop your program from breaking when it could continue. These cases are:
The top of all threads (By default, exceptions will vanish without a trace!)
Inside a main processing loop that you expect to never exit
Inside a Loop processing a list of objects where one failure shouldn't stop others
Top of the "main" thread--You might control a crash here, like dump a little data to stdout when you run out of memory.
If you have a "Runner" that runs code (for instance, if someone adds a listener to you and you call the listener) then when you run the code you should catch Exception to log the problem and let you continue notifying other listeners.
These cases you ALWAYS want to catch Exception (Maybe even Throwable sometimes) in order to catch programming/unexpected errors, log them and continue.
Unpopular opinion: Not really.
Catch all of the errors you can meaningfully recover from. Sometimes that's all of them.
In my experience, it matters more where the exception came from than which exception is actually thrown. If you keep your exceptions in tight quarters, you won't usually be swallowing anything that would otherwise be useful. Most of the information encoded in the type of an error is ancillary information, so you generally end up effectively catching all of them anyway (but you now have to look up the API docs to get the total set of possible Exceptions).
Keep in mind that some exceptions that should bubble up to the top in almost every case, such as Python's KeyboardInterrupt and SystemExit. Fortunately for Python, these are kept in a separate branch of the exception hierarchy, so you can let them bubble up by catching Exception. A well-designed exception hierarchy makes this type of thing really straightforward.
The main time catching general exceptions will cause serious problems is when dealing with resources that need to be cleaned up (perhaps in a finally clause), since a catch-all handler can easily miss that sort of thing. Fortunately this isn't really an issue for languages with defer, constructs like Python's with, or RAII in C++ and Rust.
I think a good guideline is to catch only specific exceptions from within a framework (so that the host application can deal with edge cases like the disk filling up etc), but I don't see why we shouldn't be able to catch all exceptions from our application code. Quite simply there are times where you don't want the app to crash, no matter what might go wrong.
Most of the time catching a general exception is not needed. Of course there are situations where you don't have a choice, but in this case I think it's better to check why you need to catch it. Maybe there's something wrong in your design.
Catching general exception, I feel is like holding a stick of dynamite inside a burning building, and putting out the fuze. It helps for a short while, but dynamite will blow anyways after a while.
Of corse there might be situations where catching a general Exception is necessary, but only for debug purposes. Errors and bugs should be fixed, not hidden.
For my IabManager class, which I used with in-app billing (from the TrivialDrive example online), I noticed sometimes I'd deal with a lot of exceptions. It got to the point where it was unpredictable.
I realized that, as long as I ceased the attempt at trying to consume an in-app product after one exception happens, which is where most of the exceptions would happen (in consume, as opposed to buy), I would be safe.
I just changed all the exceptions to a general exception, and now I don't have to worry about any other random, unpredictable exceptions being thrown.
Before:
catch (final RemoteException exc)
{
exc.printStackTrace();
}
catch (final IntentSender.SendIntentException exc)
{
exc.printStackTrace();
}
catch (final IabHelper.IabAsyncInProgressException exc)
{
exc.printStackTrace();
}
catch (final NullPointerException exc)
{
exc.printStackTrace();
}
catch (final IllegalStateException exc)
{
exc.printStackTrace();
}
After:
catch (final Exception exc)
{
exc.printStackTrace();
}
I have always been of the belief that if a method can throw an exception then it is reckless not to protect this call with a meaningful try block.
I just posted 'You should ALWAYS wrap calls that can throw in try, catch blocks.' to this question and was told that it was 'remarkably bad advice' - I'd like to understand why.
A method should only catch an exception when it can handle it in some sensible way.
Otherwise, pass it on up, in the hope that a method higher up the call stack can make sense of it.
As others have noted, it is good practice to have an unhandled exception handler (with logging) at the highest level of the call stack to ensure that any fatal errors are logged.
As Mitch and others stated, you shouldn't catch an exception that you do not plan on handling in some way. You should consider how the application is going to systematically handle exceptions when you are designing it. This usually leads to having layers of error handling based on the abstractions - for example, you handle all SQL-related errors in your data access code so that the part of the application that is interacting with domain objects is not exposed to the fact that there is a DB under the hood somewhere.
There are a few related code smells that you definitely want to avoid in addition to the "catch everything everywhere" smell.
"catch, log, rethrow": if you want scoped based logging, then write a class that emits a log statement in its destructor when the stack is unrolling due to an exception (ala std::uncaught_exception()). All that you need to do is declare a logging instance in the scope that you are interested in and, voila, you have logging and no unnecessary try/catch logic.
"catch, throw translated": this usually points to an abstraction problem. Unless you are implementing a federated solution where you are translating several specific exceptions into one more generic one, you probably have an unnecessary layer of abstraction... and don't say that "I might need it tomorrow".
"catch, cleanup, rethrow": this is one of my pet-peeves. If you see a lot of this, then you should apply Resource Acquisition is Initialization techniques and place the cleanup portion in the destructor of a janitor object instance.
I consider code that is littered with try/catch blocks to be a good target for code review and refactoring. It indicates that either exception handling is not well understood or the code has become an amœba and is in serious need of refactoring.
Because the next question is "I've caught an exception, what do I do next?" What will you do? If you do nothing - that's error hiding and the program could "just not work" without any chance to find what happened. You need to understand what exactly you will do once you've caught the exception and only catch if you know.
You don't need to cover every block with try-catches because a try-catch can still catch unhandled exceptions thrown in functions further down the call stack. So rather than have every function have a try-catch, you can have one at the top level logic of your application. For example, there might be a SaveDocument() top-level routine, which calls many methods which call other methods etc. These sub-methods don't need their own try-catches, because if they throw, it's still caught by SaveDocument()'s catch.
This is nice for three reasons: it's handy because you have one single place to report an error: the SaveDocument() catch block(s). There's no need to repeat this throughout all the sub-methods, and it's what you want anyway: one single place to give the user a useful diagnostic about something that went wrong.
Two, the save is cancelled whenever an exception is thrown. With every sub-method try-catching, if an exception is thrown, you get in to that method's catch block, execution leaves the function, and it carries on through SaveDocument(). If something's already gone wrong you likely want to stop right there.
Three, all your sub-methods can assume every call succeeds. If a call failed, execution will jump to the catch block and the subsequent code is never executed. This can make your code much cleaner. For example, here's with error codes:
int ret = SaveFirstSection();
if (ret == FAILED)
{
/* some diagnostic */
return;
}
ret = SaveSecondSection();
if (ret == FAILED)
{
/* some diagnostic */
return;
}
ret = SaveThirdSection();
if (ret == FAILED)
{
/* some diagnostic */
return;
}
Here's how that might be written with exceptions:
// these throw if failed, caught in SaveDocument's catch
SaveFirstSection();
SaveSecondSection();
SaveThirdSection();
Now it's much clearer what is happening.
Note exception safe code can be trickier to write in other ways: you don't want to leak any memory if an exception is thrown. Make sure you know about RAII, STL containers, smart pointers, and other objects which free their resources in destructors, since objects are always destructed before exceptions.
Herb Sutter wrote about this problem here. For sure worth reading.
A teaser:
"Writing exception-safe code is fundamentally about writing 'try' and 'catch' in the correct places." Discuss.
Put bluntly, that statement reflects a fundamental misunderstanding of exception safety. Exceptions are just another form of error reporting, and we certainly know that writing error-safe code is not just about where to check return codes and handle error conditions.
Actually, it turns out that exception safety is rarely about writing 'try' and 'catch' -- and the more rarely the better. Also, never forget that exception safety affects a piece of code's design; it is never just an afterthought that can be retrofitted with a few extra catch statements as if for seasoning.
As stated in other answers, you should only catch an exception if you can do some sort of sensible error handling for it.
For example, in the question that spawned your question, the questioner asks whether it is safe to ignore exceptions for a lexical_cast from an integer to a string. Such a cast should never fail. If it did fail, something has gone terribly wrong in the program. What could you possibly do to recover in that situation? It's probably best to just let the program die, as it is in a state that can't be trusted. So not handling the exception may be the safest thing to do.
If you always handle exceptions immediately in the caller of a method that can throw an exception, then exceptions become useless, and you'd better use error codes.
The whole point of exceptions is that they need not be handled in every method in the call chain.
The best advice I've heard is that you should only ever catch exceptions at points where you can sensibly do something about the exceptional condition, and that "catch, log and release" is not a good strategy (if occasionally unavoidable in libraries).
I was given the "opportunity" to salvage several projects and executives replaced the entire dev team because the app had too many errors and the users were tired of the problems and run-around. These code bases all had centralized error handling at the app level like the top voted answer describes. If that answer is the best practice why didn't it work and allow the previous dev team to resolve issues? Perhaps sometimes it doesn't work? The answers above don't mention how long devs spend fixing single issues. If time to resolve issues is the key metric, instrumenting code with try..catch blocks is a better practice.
How did my team fix the problems without significantly changing the UI? Simple, every method was instrumented with try..catch blocked and everything was logged at the point of failure with the method name, method parameters values concatenated into a string passed in along with the error message, the error message, app name, date, and version. With this information developers can run analytics on the errors to identify the exception that occurs the most! Or the namespace with the highest number of errors. It can also validate that an error that occurs in a module is properly handled and not caused by multiple reasons.
Another pro benefit of this is developers can set one break-point in the error logging method and with one break-point and a single click of the "step out" debug button, they are in the method that failed with full access to the actual objects at the point of failure, conveniently available in the immediate window. It makes it very easy to debug and allows dragging execution back to the start of the method to duplicate the problem to find the exact line. Does centralized exception handling allow a developer to replicate an exception in 30 seconds? No.
The statement "A method should only catch an exception when it can handle it in some sensible way." This implies that developers can predict or will encounter every error that can happen prior to release. If this were true a top level, app exception handler wouldn't be needed and there would be no market for Elastic Search and logstash.
This approach also lets devs find and fix intermittent issues in production! Would you like to debug without a debugger in production? Or would you rather take calls and get emails from upset users? This allows you to fix issues before anyone else knows and without having to email, IM, or Slack with support as everything needed to fix the issue is right there. 95% of issues never need to be reproduced.
To work properly it needs to be combined with centralized logging that can capture the namespace/module, class name, method, inputs, and error message and store in a database so it can be aggregated to highlight which method fails the most so it can be fixed first.
Sometimes developers choose to throw exceptions up the stack from a catch block but this approach is 100 times slower than normal code that doesn't throw. Catch and release with logging is preferred.
This technique was used to quickly stabilize an app that failed every hour for most users in a Fortune 500 company developed by 12 Devs over 2 years. Using this 3000 different exceptions were identified, fixed, tested, and deployed in 4 months. This averages out to a fix every 15 minutes on average for 4 months.
I agree that it is not fun to type in everything needed to instrument the code and I prefer to not look at the repetitive code, but adding 4 lines of code to each method is worth it in the long run.
I agree with the basic direction of your question to handle as many exceptions as possible at the lowest level.
Some of the existing answer go like "You don't need to handle the exception. Someone else will do it up the stack." To my experience that is a bad excuse to not think about exception handling at the currently developed piece of code, making the exception handling the problem of someone else or later.
That problem grows dramatically in distributed development, where you may need to call a method implemented by a co-worker. And then you have to inspect a nested chain of method calls to find out why he/she is throwing some exception at you, which could have been handled much easier at the deepest nested method.
The advice my computer science professor gave me once was: "Use Try and Catch blocks only when it's not possible to handle the error using standard means."
As an example, he told us that if a program ran into some serious issue in a place where it's not possible to do something like:
int f()
{
// Do stuff
if (condition == false)
return -1;
return 0;
}
int condition = f();
if (f != 0)
{
// handle error
}
Then you should be using try, catch blocks. While you can use exceptions to handle this, it's generally not recommended because exceptions are expensive performance wise.
If you want to test the outcome of every function, use return codes.
The purpose of Exceptions is so that you can test outcomes LESS often. The idea is to separate exceptional (unusual, rarer) conditions out of your more ordinary code. This keeps the ordinary code cleaner and simpler - but still able to handle those exceptional conditions.
In well-designed code deeper functions might throw and higher functions might catch. But the key is that many functions "in between" will be free from the burden of handling exceptional conditions at all. They only have to be "exception safe", which does not mean they must catch.
I would like to add to this discussion that, since C++11, it does make a lot of sense, as long as every catch block rethrows the exception up until the point it can/should be handled. This way a backtrace can be generated. I therefore believe the previous opinions are in part outdated.
Use std::nested_exception and std::throw_with_nested
It is described on StackOverflow here and here how to achieve this.
Since you can do this with any derived exception class, you can add a lot of information to such a backtrace!
You may also take a look at my MWE on GitHub, where a backtrace would look something like this:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
I feel compelled to add another answer although Mike Wheat's answer sums up the main points pretty well. I think of it like this. When you have methods that do multiple things you are multiplying the complexity, not adding it.
In other words, a method that is wrapped in a try catch has two possible outcomes. You have the non-exception outcome and the exception outcome. When you're dealing with a lot of methods this exponentially blows up beyond comprehension.
Exponentially because if each method branches in two different ways then every time you call another method you're squaring the previous number of potential outcomes. By the time you've called five methods you are up to 256 possible outcomes at a minimum. Compare this to not doing a try/catch in every single method and you only have one path to follow.
That's basically how I look at it. You might be tempted to argue that any type of branching does the same thing but try/catches are a special case because the state of the application basically becomes undefined.
So in short, try/catches make the code a lot harder to comprehend.
Besides the above advice, personally I use some try+catch+throw; for the following reason:
At boundary of different coder, I use try + catch + throw in the code written by myself, before the exception being thrown to the caller which is written by others, this gives me a chance to know some error condition occured in my code, and this place is much closer to the code which initially throw the exception, the closer, the easier to find the reason.
At the boundary of modules, although different module may be written my same person.
Learning + Debug purpose, in this case I use catch(...) in C++ and catch(Exception ex) in C#, for C++, the standard library does not throw too many exception, so this case is rare in C++. But common place in C#, C# has a huge library and an mature exception hierarchy, the C# library code throw tons of exception, in theory I(and you) should know every exceptions from the function you called, and know the reason/case why these exception being thrown, and know how to handle them(pass by or catch and handle it in-place)gracefully. Unfortunately in reality it's very hard to know everything about the potential exceptions before I write one line of code. So I catch all and let my code speak aloud by logging(in product environment)/assert dialog(in development environment) when any exception really occurs. By this way I add exception handling code progressively. I know it conflit with good advice but in reality it works for me and I don't know any better way for this problem.
You have no need to cover up every part of your code inside try-catch. The main use of the try-catch block is to error handling and got bugs/exceptions in your program. Some usage of try-catch -
You can use this block where you want to handle an exception or simply you can say that the block of written code may throw an exception.
If you want to dispose your objects immediately after their use, You can use try-catch block.
Why is it a "bad idea" to throw your own exceptions?
found here
In general, it is perfectly fine to throw your own exceptions. Perhaps what you meant to ask was "When is it not necessarily a good idea to throw my own exception?"
One case is when you should be throwing a standard exception. For example, if your method takes a file name and is supposed to return a file, you should probably throw your platform's standard FileNotFoundException rather than throw PeanutPowersFileNotFoundException. If you really want to throw your own exception, you should probably have it extend the standard FileNotFoundException.
Update: Bloch explains this in Item 60 of Effective Java
It's not. You should create and throw custom exceptions whenever you have an exceptional situation.
It isn't provided they are derived from whatever the standard base exception type is (std::exception in c++, or Exception in python, etc...)
If they _aren't_derived from the normal base type, then other people may not catch them when they are expecting to catch all exceptions - which would be a bad thing.
It's not wrong to create your own exception type. However, before going through creating your own, you should check whether your framework already provides an exception that fits.
From the .Net design guidelines:
Consider throwing existing exceptions
residing in the System namespaces
instead of creating custom exception
types.
Do create and throw custom exceptions
if you have an error condition that
can be programmatically handled in a
different way than any other existing
exceptions. Otherwise, throw one of
the existing exceptions.
Do not create and throw new exceptions
just to have your team's exception.
I believe you might be asking why is it a bad idea to re-throw exceptions.
By "rethrow", I mean catching an exception and than generating a new one and throwing it. This can be problematic, as you could end up consuming the original stack trace and loosing all context of the error.
You should not invent your own type of Exception, unless you have something extra you want to add to the Exception type.
If you want to tell the user of your API that they have provided an invalid argument, you should throw an ArgumentException, but if your library fails because of some library specific reason, that you can't convey in a regular exception, you should roll your own and let it contain the info the developer needs.
To continue Peter's response another case when throwing an exception is not a good idea is if you use throwing exceptions to control the business logic of your program.
As long as the exception you are throwing is derived from a proper object, and conveys just that - exceptional situation, throwing an exception is totally acceptable.
Using throwing exceptions to control business logic in addition to being a bad design pattern has also performance implications - throwing and catching exceptions is rather expensive as compared to branching based on the results returned from the method
There's nothing wrong with creating your own exceptions, which can be tailored to convey exactly the information which is appropriate for your situation. A ConfigFileNotFoundException conveys more information than a FileNotFoundException (which file didn't we find?).
But, by all means, make sure that you catch and handle each and every custom exception inside of your code. When the exception flies to some place outside your module (call it package, call it namespace), those folks out there will not even know that it exists, much less what to do with it. Except for a catch (Throwable t) {/* whut? */}.
To me it seems that the question is to catch inexperienced candidates trying to fake experience. There's nothing wrong about throwing your own exceptions in my opinion, and as you can see to everyone else that answered here.
It's not a bad idea at all. If an exceptional situation arises, an exception should be thrown to handle it, especially if you're designing code that others may use, may receive bad input, etc.
It is a bad idea to use exceptions where they're not absolutely necessary, such as situations that are recoverable by normal checks in code or as part of normal execution, since they do have a lot of overhead associated with them. I imagine that's where you may have gotten the idea that they're a bad idea in general. But for what they're meant to do (flagging an exceptional situation that your code isn't equipped to handle), they're absolutely the best tool.
And if you do create custom exceptions for code others might use, do document what they are and what they mean. That way later users of your code will know that they're possible and what they mean if they arise, and can handle them appropriately.
At what point during development do you typically implement your exception handlers? Do you write them at the same time as you write the surrounding code, or do you write your code and then come back to "harden" it later?
I typically do the latter so that I can see exactly where and how my code fails, but I worry that my code isn't as resilient as it could be if I would have written the exception handlers right away.
At the same time, I don't want to spend a whole bunch of development time figuring out all the possible ways that my code could fail when there are other implementation details that I haven't settled on yet.
I'm curious as to how other developers do this.
Update: I just wanted to thank everyone for their answers!
I either write the exception handlers immediately, or I allow the exceptions to propagate upwards. I'm a big fan of what I call the "You're Not Going To Go Back And Fix It Later, Are You?" principle. You say you will, but honestly, once you get it working, you're not going to go back and fix it later, are you? Just get it right right now! Write your exception handlers right away, or add a throws clause and make it somebody else's problem. Do the right thing right now.
But you know what, sometimes you can't. Whatever you do, do not swallow exceptions with empty exception handlers! This is evil:
try {
connection.close();
}
catch (Exception e) {
// TODO Auto-generated code
}
I drop kick anybody on my team who checks that in.
If you really don't know what to do about an exception and cannot add a throws clause to propagate it upwards, at least do something halfway responsible. Print a stack trace, if nothing else. It's not ideal but at least you're not hiding errors.
catch (IOException exception) {
exception.printStackTrace();
}
Logging it via your application's logging system is better, though you shouldn't make a habit of it. It's supposed to be the caller's responsibility to handle these kinds of things.
catch (IOException exception) {
log.error(exception, "Unable to open configuration file %s.", fileName);
}
As a last resort, you can do an end run around your throws clause by wrapping your exception in a RuntimeException. At least you're giving somebody higher up the call chain a chance to handle the error, which is normally the Right Thing To Do.
catch (IOException exception) {
throw new RuntimeException(exception);
}
In my exception handler I usually raise a higher-level exception. For example, when parsing a file in Python, some string, list and dict operations may raise ValueError, IndexError or KeyError. These exceptions are usually not helpful for the caller, so I write an exception handler, which raises a descriptive MyParseError. I do this at the same time when writing the method, but later, when writing the test, I sometimes make the exception message more verbose.
If I am calling an API then I look at what exceptions can be thrown and decide based on the list. The exceptions that can be thrown generally fall into categories:
Improbable in my view this will get thrown - make sure that code fails nicely
Realistic that this will get thrown - what should I do if this gets called?
Certain that this will get thrown based on current inputs - add validation to inputs to stop it getting thrown
Could I raise a more relevant exception? - if an exception is likely to get to get called would it be clearer for other calling code if I raised a new/different exception
In general I think it is always good practice to have catch all try catch blocks high up in the call stack that can catch general exceptions (Throwable) and then report these nicely to the user - perhaps with an interface that will then email the error and stacktrace to the development team and ask for user comments.
Sometimes both. In some cases I know of the exceptions that can be thrown and I want to handle as I'm writing the code, and so I write the handlers right then and there. Other times I don't know of all of the exceptions and find them later, either through documentation, testing or both.
It's a combination of both. There are things that I know can go wrong like database connections, configuration settings, file read/writes as well as the red flags from the functional/tech specifications. I try to setup the try/catch for those ASAP.
As the application gets bigger over time I then start to see patterns and trends with either how the user is using the application and or how me and or the team has developed it and add those try/catches as needed.
It kind of depends on the nature of the project you are working on. In my case, if I'm familiar with the logic of the system, I should know where, and how, to handle exceptions even before writing code. On the other hand, I would write my stuff, test it and then write the handlers.
during development, when:
a unit test require it
when some presentation/persistence code require it
EDIT
in Java sometimes, you must take care error handling at very early stage (checked exceptions) and sometimes this is very annoying.
My approach is to address exception handling immediately, since it's not some aimless burden that you can happily postpone.
Just handle the exceptions that apply at the point that you write your code, propagate all those that do not matter, and only come back later to fix whatever is broken, saves you a lot of tears.
As a rule, not only do I write my exception handling when I'm writing the code, but I try to write the code to avoid exceptions in the first place. The advantages are that if I know I need to handle an exception I remember to and if I can avoid an exception that is always a plus. I also test my code after I've written it using boundary conditions to see if there's any possible exceptions that I may have missed.
Writing the handlers when you are writing the actual code is the best habbit i guess because you are very clear of the failures that may occur although you can add others when you discover it.
handling the exception may be tedious for the first time but it would save lot of time while debugging for some error i.e support.
Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.
Obviously this is one of those questions where the only real answer is "it depends."
The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.
The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.
The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:
try {
something();
} catch (Exception ex) {}
or this in Python:
try:
something()
except:
pass
Because these can be some of the hardest issues to track down.
A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can.
Unless you are doing some logging and clean up code in the front end of your application, then I think it is bad to catch all exceptions.
My basic rule of thumb is to catch all the exceptions you expect and anything else is a bug.
If you catch everything and continue on, it's a bit like putting a sticking plaster over the warning light on your car dashboard. You can't see it anymore, but it doesn't mean everything is ok.
Yes! (except at the "top" of your application)
By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem. You are stating that this is a recoverable situation. Catching Exception or SystemException means that you will catch problems like IO errors, network errors, out-of-memory errors, missing-code errors, null-pointer-dereferencing and the likes. It is a lie to say that you can deal with these.
In a well organised application, these unrecoverable problems should be handled high up the stack.
In addition, as code evolves, you don't want your function to catch a new exception that is added in the future to a called method.
In my opinion you should catch all exceptions you expect, but this rule applies to anything but your interface logic. All the way down the call stack you should probably create a way to catch all exceptions, do some logging/give user feedback and, if needed and possible, shut down gracefully.
Nothing is worse than an application crashing with some user unfriendly stacktrace dumped to the screen. Not only does it give (perhaps unwanted) insight into your code, but it also confuses your end-user, and sometimes even scares them away to a competing application.
There's been a lot of philosophical discussions (more like arguments) about this issue. Personally, I believe the worst thing you can do is swallow exceptions. The next worst is allowing an exception to bubble up to the surface where the user gets a nasty screen full of technical mumbo-jumbo.
Well, I don't see any difference between catching a general exception or a specific one, except that when having multiple catch blocks, you can react differently depending on what the exception is.
In conclusion, you will catch both IOException and NullPointerException with a generic Exception, but the way your program should react is probably different.
The point is twofold I think.
Firstly, if you don't know what exception has occurred how can you hope to recover from it. If you expect that a user might type a filename in wrong then you can expect a FileNotFoundException and tell the user to try again. If that same code generated a NullReferenceException and you simply told the user to try again they wouldn't know what had happened.
Secondly, the FxCop guidelines do focus on Library/Framework code - not all their rules are designed to be applicable to EXE's or ASP.Net web sites. So having a global exception handler that will log all exceptions and exit the application nicely is a good thing to have.
The problem with catching all exceptions is that you may be catching ones that you don't expect, or indeed ones that you should not be catching. The fact is that an exception of any kind indicates that something has gone wrong, and you have to sort it out before continuing otherwise you may end up with data integrity problems and other bugs that are not so easy to track down.
To give one example, in one project I implemented an exception type called CriticalException. This indicates an error condition that requires intervention by the developers and/or administrative staff otherwise customers get incorrectly billed, or other data integrity problems might result. It can also be used in other similar cases when merely logging the exception is not sufficient, and an e-mail alert needs to be sent out.
Another developer who didn't properly understand the concept of exceptions then wrapped some code that could potentially throw this exception in a generic try...catch block which discarded all exceptions. Fortunately, I spotted it, but it could have resulted in serious problems, especially since the "very uncommon" corner case that it was supposed to catch turned out to be a lot more common than I anticipated.
So in general, catching generic exceptions is bad unless you are 100% sure that you know exactly which kinds of exceptions will be thrown and under which circumstances. If in doubt, let them bubble up to the top level exception handler instead.
A similar rule here is never throw exceptions of type System.Exception. You (or another developer) may want to catch your specific exception higher up the call stack while letting others go through.
(There is one point to note, however. In .NET 2.0, if a thread encounters any uncaught exceptions it unloads your whole app domain. So you should wrap the main body of a thread in a generic try...catch block and pass any exceptions caught there to your global exception handling code.)
I would like to play devil's advocate for catching Exception and logging it and rethrowing it. This can be necessary if, for example, you are somewhere in the code and an unexpected exception happens, you can catch it, log meaningful state information that wouldn't be available in a simple stack trace, and then rethrow it to upper layers to deal with.
There are two completely different use cases. The first is the one most people are thinking about, putting a try/catch around some operation that requires a checked exception. This should not be a catch-all by any means.
The second, however, is to stop your program from breaking when it could continue. These cases are:
The top of all threads (By default, exceptions will vanish without a trace!)
Inside a main processing loop that you expect to never exit
Inside a Loop processing a list of objects where one failure shouldn't stop others
Top of the "main" thread--You might control a crash here, like dump a little data to stdout when you run out of memory.
If you have a "Runner" that runs code (for instance, if someone adds a listener to you and you call the listener) then when you run the code you should catch Exception to log the problem and let you continue notifying other listeners.
These cases you ALWAYS want to catch Exception (Maybe even Throwable sometimes) in order to catch programming/unexpected errors, log them and continue.
Unpopular opinion: Not really.
Catch all of the errors you can meaningfully recover from. Sometimes that's all of them.
In my experience, it matters more where the exception came from than which exception is actually thrown. If you keep your exceptions in tight quarters, you won't usually be swallowing anything that would otherwise be useful. Most of the information encoded in the type of an error is ancillary information, so you generally end up effectively catching all of them anyway (but you now have to look up the API docs to get the total set of possible Exceptions).
Keep in mind that some exceptions that should bubble up to the top in almost every case, such as Python's KeyboardInterrupt and SystemExit. Fortunately for Python, these are kept in a separate branch of the exception hierarchy, so you can let them bubble up by catching Exception. A well-designed exception hierarchy makes this type of thing really straightforward.
The main time catching general exceptions will cause serious problems is when dealing with resources that need to be cleaned up (perhaps in a finally clause), since a catch-all handler can easily miss that sort of thing. Fortunately this isn't really an issue for languages with defer, constructs like Python's with, or RAII in C++ and Rust.
I think a good guideline is to catch only specific exceptions from within a framework (so that the host application can deal with edge cases like the disk filling up etc), but I don't see why we shouldn't be able to catch all exceptions from our application code. Quite simply there are times where you don't want the app to crash, no matter what might go wrong.
Most of the time catching a general exception is not needed. Of course there are situations where you don't have a choice, but in this case I think it's better to check why you need to catch it. Maybe there's something wrong in your design.
Catching general exception, I feel is like holding a stick of dynamite inside a burning building, and putting out the fuze. It helps for a short while, but dynamite will blow anyways after a while.
Of corse there might be situations where catching a general Exception is necessary, but only for debug purposes. Errors and bugs should be fixed, not hidden.
For my IabManager class, which I used with in-app billing (from the TrivialDrive example online), I noticed sometimes I'd deal with a lot of exceptions. It got to the point where it was unpredictable.
I realized that, as long as I ceased the attempt at trying to consume an in-app product after one exception happens, which is where most of the exceptions would happen (in consume, as opposed to buy), I would be safe.
I just changed all the exceptions to a general exception, and now I don't have to worry about any other random, unpredictable exceptions being thrown.
Before:
catch (final RemoteException exc)
{
exc.printStackTrace();
}
catch (final IntentSender.SendIntentException exc)
{
exc.printStackTrace();
}
catch (final IabHelper.IabAsyncInProgressException exc)
{
exc.printStackTrace();
}
catch (final NullPointerException exc)
{
exc.printStackTrace();
}
catch (final IllegalStateException exc)
{
exc.printStackTrace();
}
After:
catch (final Exception exc)
{
exc.printStackTrace();
}