Is it wrong to thow or catch the Exception Class (every Exception possible)? - exception

I know that a question like this probably depends on what the programmer intends his program to do however at school we were taught to never throw or catch Exception (the class) and rather make sure it throws one of the subclasses more specific to the kind of Runtime error we expect can happen (eg IllegalArgumentException). However, I'm working now and in the 'real world' I see a lot of scenarios in code I work on where the previous programmers threw Exception for everything in a method or catch Exception like that rather than one of its more specific subclasses.
So I'm wondering, Is it ok to throw and catch everything like this, is it bad programming to do so?

My idea is, the way of handle the exceptions should also depend on the type of the application you are creating. For example if you are developing some kind of a framework or a library you should not try to print error messages or log them, you have throw them because it will be responsibility of the other developers who are using your framework/library to handle the exceptions gracefully when they are using your code.
If you are developing some kind of a front end application then you should be more delicate with exception handling. I think it's better you use you own exception classes when possible, because that will help you to pin point the bugs or runtime issues in your application later. When you handle exceptions you should always go from more specific exceptions to general exceptions. And finally you should handle the exceptions of the "Exception" super class so it will make sure that your application doesn't crash, preferably you should have a try-catch block in the main entry point of your application. What ever happens in handling exceptions logging the errors is a good practice when it comes diagnosing the errors later.

It is not wrong to do that but it can make your debugging life very difficult. Many people will catch the exception class and log the Exception.Message. There is not enough detail and, especially if you're working on large systems where you can't always step through the live code etc, it will be a tedious task.
I tend to catch specific exceptions and handle them accordingly BUT I also catch the Exception class to make sure all exceptions are caught going forward (An object might be changed to include more exceptions in future framework versions).

It is bad practice, just as you have learnt.
One major exception to the rule is a top-level exception handler (to catch unhandled exceptions) - the purpose of this would be to log exception so they can be read by a developer later and used to fix the application (and would normally rethrow in order to crash the application - rather than leaving it in an inconsistent state).

Related

Is catching only "Exception" acceptable? [duplicate]

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();
}

Why is it a "bad idea" to throw your own exceptions?

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.

The right time to handle all exceptions

I've done a few projects so far, and i've noticed that every single one i've written entirely without any exception handling, then at the end I do a lot of tests and handle them all.
is it right? i get thousands of exceptions while testing (which I fix right away) that if i've handled it i wouldn't see exactly where it is(when not using breakpoints or displaying it anywhere.. but it doesn't seem as practical) So I fix issues by checking any exceptions, then in the end I handle them anyway for any possible one that might have escaped (of course).
What about you? when do you guys take care of exceptions ?
Personally, I always define a global unhandled exception manager appropriate to the application type and have that log and email exceptions to my dev team. During QA, we'll then start to add specific exception management to routines that have predictable (and recoverable) issues. In every case possible, we add defensive programming code so that exceptions don't happen at all. (There's no need to trap an exception if you can test before you try code that could fail.)
My apps tend to end up with lots of defensive code (which should be built in from the start) and only some specific exception handling.
I prefer test-driven development. If there is an expected error condition, then test for it. If an unexpected error crops up, make a test for it, then fix it.
I would say that this is backwards (but common).
You might want to look into test driven development, and test first design
Hint: think of a behavior, write code to test for it, add it to your application.
I would definitely consider the exceptions thrown as you develop each interface and module.
That way you can test that they're reliably thrown (when you expect and not when you don't). Components consuming these components can then be written to be aware of these exceptions and handle (or not as they require).
It seems to me that you're ignoring some functionality of the components you're developing. I'll virtually always test for both correct functionality and the exceptional circumstances, to cover as many scenarios as I can as early as I can.
The answer to this one is a very clear "it depends".
You need to look at the specific situation; is an exception being thrown in a specific piece of code where it's possible to recover or handle the "exceptional" situation resulting in the exception being thrown? In that case, yes, catch the exception and deal with it at that level.
On the other hand, are you talking about non-recoverable errors? Then sure, catch them at a more global level, or possibly not at all (ie if there's nothing you can do about the exception, why are you catching it?)
The rule for where to catch exceptions usually is: wherever is the place you can meaningfully handle them.
Sometimes it depends upon the technology or target platform. I usually prefer an exception handling layer that takes care of all the exceptions. Each and every block of code is inside a try catch block.
Bottom line is that no exception should get caught by the OS or any other entity outside the program or code.
The beauty of exceptions compared to say returning error codes from API's is that you don't have to check for exceptions at every layer in your code. You can catch specific exceptions to determine specific error conditions and perhaps handle the error or rethrow a more appropriate exception. You also have to catch exceptions at a high level in your application to avoid unhandled exceptions.
One thing to note is that generally the user of the exception is the developer and not the end-user. The later normally doesn't appreciate the technical details of exceptions.
The most common thing I've seen is developers making a conscious choice as to what level to handle exceptions, and allow them to be thrown. Typically it will be at the level of a worker thread, or a high level of business logic. Allow the exceptions to happen, and have a blanket method of handling / logging them and protecting the user from them.
Timing is the only difference between what typically happens and what you do. Plan for it in your applications from the beginning, and do exception handling at high levels.
Fixing specific exceptions is done via your method of fix it when it's a problem. Sometimes a library I use will needlessly use exceptions to communicate information, and I will add specialized exception handling around all calls to that library. Often I will do this in a wrapper class that hides the implementation and exception handling from the rest of my application.

When do you write your exception handlers?

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.

Is it really that bad to catch a general exception?

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();
}