use catch throwable or catch Exception in new thread of execution - java

I need to find out best-practice for try-catch when launching a new thread.
Personally, I prefer Option 2.
Which option is the best-practice? Are there any factors that might make either option a best practice in some situations and not others?
Option 1
public void run(){
try{
//do something
}catch(Exception e){
// log
}
}
Option 2
public void run(){
try{
//do something
}catch(Throwable t){
// log
}
}
EDIT: Assume that you are writing the code that has to meet a stringent code review.
EDIT 2: I know the difference between the above two options. I am just curious about what is seen as '100% correct' by others.

I would use setDefaultUncaughtExceptionHandler(...) on the thread to catch what the runnable does not handle properly, but when it comes to the runnable itself, it really depends on what it has to achieve and to reasonably anticipate considering a reasonable execution context.
On the other side, creating a separate thread to execute a runnable is not a good strategy IMHO, FutureTask deals with these issues better.

In a root exception handler that simply logs whatever went wrong, distinguishing between Error and Exception is pointless, so catching Throwable is perfectly acceptable.
If instead you were writing some retry logic, I'd catch Exception, since there really is no point retrying after an Error - in fact, it could be dangerous, because the error was thrown in code that was not exception safe, and thus might have left the system in an inconsistent state.
Therefore, it depends on what kind of exception handler you are writing.

It is never advisable to catch Throwable since this includes errors that cannot be handled or avoided such as out of memory error and so on. Thus it is generally much better to catch Exception and not catch Throwable. Sometimes it is unavoidable such as when calling invoke method or other reflection methods.

What you are trying to ask about is the concept of a fault barrier and the correct way to implement one should be a standard defined by the project you are working on or the framework you are using.
If your project has a policy to log all exceptions/errors and not let anything print to standard error, you might want to look into using an UncaughtExceptionHandler.
A general best practice would be to catch only instances of RuntimeException.
public void run(){
try{
//do something
}catch(RuntimeException e){
// log
}
}
Catching Exception is too general because the Java language requires programs to deal with checked exceptions. By catching even checked exceptions at your fault barrier you are allowing the code in the //do something block to be sloppy and not handle checked exceptions.
Catching Error or Throwable is also generally considered a bad practice since an Error typically indicates that the JVM is in a state where it can not continue to function meaningfully.
Here is a good (and somewhat relevant) article on exception handling: http://www.oracle.com/technetwork/articles/entarch/effective-exceptions-092345.html

Related

catching exception and error

We have a piece of code for reading from queue
while(true){
try {
message = readMessageFromQueue();
processMesage(message); //Writes into DB and some other operation
}catch(Exception e) {
log the exception
}
}
Now there are ten threads which are spawned using executor service with the aim of running forever. However we have noticed after sometime we deploy(it can be 10-15 days or month) the number of thread is getting reduced(Write per second is also decreasing because of that).
The question is should we catch Error or only exception in the code which we want to run forever like this and is catching Exception can cause this problem ?
Yes, it's better to catch a Throwable there, not just Exception. Depending on your processing you might get, for example, a StackOverflowError that will kill your thread without logging. You might not be able to recover from it, but at least you can debug the problem latter.
From what I understand, you're asking if it is okay to catch by general Exception versus specific exceptions, like ArrayOutOfBoundsException. So, I guess my answer come down to whatever you prefer. You can catch by Exception, which isn't usually advised because you should always know what your code is doing and thus what could go wrong, but it does accomplish your tasks. Now, the reason you should catch by specific exceptions is that you can have different methods of handling different errors. Maybe the way you are handling the error isn't universally applicable to all errors, so when the thread sees an exception it isn't designed to expect, it crashes leaving you with one less thread.
I prefer catching specific exceptions of I can do something gracefully with that failure (like retry or do some default behavior). But if an exception means the program can't continue at all regardless, than catching the most generic exception and terminating is fine.
catching Exception is a "shotgun" approach to exception handling - "Whatever exception you will throw, I will catch it!".
catching a specific, ideally custom Exception is preferred mainly because you know where that exception is thrown, and you can gracefully handle that exception, or do some methods specifically for a certain exception. Therefore gives you more control of your application.
hope this helps.

Is it okay to handle Runtime exceptions?

It's generally a good practice to not handle runtime exceptions.
I have this scenario :
/**boolean returns false if the method execution fails,
so that an error can be shown to user*/
boolean saveData()
{
try
{
//Some database calls that throw only Runtime exceptions
}
catch(Exception e)
{
//Log the exception and return false
return false;
}
return true;
}
So from the Servlet calling it will get a boolean value. If it's false, we show a message 'Save Not sucessful'. Is this okay or is there a better way of doing it ?
Is it okay to handle Runtime exceptions?
As long as you can do something intelligent at that point, yes. This 'never catch run-time exceptions' is pure nonsense. You'll probably want to log them and do other things, as well.
It's generally a good practice to not handle runtime exceptions.
This sentence implies a false premise: the question is not whether, but when to catch runtime exceptions.
At some point in your code you should definitely have a "catch-all" exception handler. This point is called the exception barrier, and it is high enough in the call stack to encompass a complete unit of work (basically, the scope of one database transaction).
This should be your governing principle:
if an exception must cause the current unit of work to be aborted (rolled back), then do not catch that exception until the exception barrier;
if an exception is of local character only, and its appearance only means taking a different route to the handling of the request, then do catch and handle it early.
Note that the above doesn't use the fruitless checked/unchecked distinction. Most modern frameworks completely avoid checked exceptions and go out of their way to shield the programmer from such exceptions being thrown from lower-level code.
In practice, more than 90% of all exceptions are of the first, aborting kind. This is what is meant by the term "unrecoverable"—it means you can't continue what you are doing right now, but the server can stay up and process all other requests. I see many people confusing this with "the JVM is about to die", but exceptions which have that meaning are exceedingly rare and usually there is no special handling code for them.
Lastly, note that the "catch-all" handler should catch not only RuntimeExceptions but also Errors because you want every exception logged the same way. If you let an exception escape your application code, there is no knowing what behavior it will cause. Note that there are some common errors, like StackOverflow and OutOfMemory, which can in principle cause unrecoverable damage and therefore rightfully belong to the Error hierarchy, yet in most real-life cases do no damage beyond aborting the current request. You definitely do not want to shut down your service at the first sight of such an error.
No, catching a general Exception will mask any other problems you don't want to catch. Better catching specific exceptions making it harder for unexpected ones to go missing.
I guess your question has two aspects: 1) Handling RuntimeExceptionas the heading suggested and 2) handling generic Exception these are two different things.
The Javadoc of RuntimeExcepton list a bunch of its subclasses (NullPointerException..etc). If you look carefully, these are nothing but the programming errors and instead of handling them in catch block, should be corrected the the code itself so that they do not occur.
Handling generic Exception is generally referred as a poor practice and rightly so because it hides the specific exceptions which might need different handling.
But in case similar to yours, if there is a Servlet giving a call to method there has to be a graceful way to tell the user that there was some problem with the application while processing the request instead if showing the stacktrace.
So what you are doing could be one way of handling and as a good practice keep track of errors/exceptions in the log and correct any RuntimeExceptions
boolean returns false if the method execution fails,
so that an error can be shown to user
This is a clear reason for the method to throw an exception. It is why the exception mechanism exists in the first place. Best practice is to use exceptions for these types of circumstances, not boolean signals.
Anytime you follow this kind of pattern, you suffer in several ways
The caller cannot be sure what really happened. Was there a communication failure? Was the data corrupted? There is no way to tell when you return a simple "FAILED" signal.
Because the caller cannot know what happened, you take away options for the caller. Maybe the caller could do something in certain error cases.
You increase the potential for data errors. Again, since the caller cannot know why it failed, the caller may make assumptions about why it failed and continue in cases when the entire program should halt. If the program continues, it may decide to process invalid data when it really should stop.
I highly recommend reading the sections on exception handling in Effective Java. Basically, if you can't do anything meaningful with an Exception in your method, you should allow it to pass up the stack. In the worst case scenario, the API you reference throws a generic checked exception, giving you one of three choices (EDIT: Changed to void return type because the boolean return type no longer has any meaning -- you either succeed or throw an exception)
-Create your own.
// "MyFatalException" would be a checked Exception
public void saveData() throws MyFatalException{
try{
// ... do stuff that throws Exception
}catch(Exception e){
throw new MyFatalException("Unable to save Data due to a general exception"+
" thrown by foo.bar()", e);
}
}
-Throw an existing type (my preference is for subclasses of RuntimeException)
public void saveData() throws IllegalStateException{
try{
// ... do stuff that throws Exception
}catch(Exception e){
throw new IllegalStateException("Unable to save Data due to a general exception"+
" thrown by foo.bar()", e);
}
-Declare to throw a generic Exception and let it pass up (I do NOT recommend this, but you'll see many developers who do this)
public void saveData() throws Exception{
// no try/catch needed. Just make the call
}
The general concept is that frameworks or APIs would throw a RuntimeException only in situations when the error is not recoverable in code. e.g: your Db is down, or your server socket is down and things like that.
Though its not bad to catch such exceptions but whats actually thoughtful is what do you intend to do after catching them. e.g: people prefer to catch DB level connection problems and errors which are runtime exception subclasses and show error pages on their websites. Checked exceptions are usually for code level situational cases and catching them and handling is what code is expected to do.
In case you try something like this, since you don't want your users to error page you can do this, provided you caught all other exceptions before this.
boolean saveData()
{
try
{
//Some database calls that throw only Runtime exceptions
}catch(db_Connectivity_Exception e){
//exception like credentials invalid
}catch(db_table_Exception e){
//table desc. changed
}
catch(Exception e)
{
//Log the exception and return false
//Since you are going to log your error I hope is not harmfu
return false;
}
return true;
}
Still this is not best practice

Why is the Catch(Exception) almost always a bad Idea?

Why is the catch(Exception) almost always a bad Idea?
Because when you catch exception you're supposed to handle it properly. And you cannot expect to handle all kind of exceptions in your code. Also when you catch all exceptions, you may get an exception that cannot deal with and prevent code that is upper in the stack to handle it properly.
The general principal is to catch the most specific type you can.
Short story: it's called bug masking. If you have a piece of code which is not working well and throwing exceptions (or you pass malformed input to that piece of code) and you just blind your eyes by catching all possible exceptions, you will actually never uncover the bug and fix it.
You should only catch exceptions if you can properly handle them. As you cannot properly handle all possible exceptions you should not catch them :-)
It depends on what you need. If you need to handle different types of exceptions in different ways then you should use multiple catch blocks and catch as much specific exceptions as you can.
But sometimes you may need to handle all exceptions in the same way. In such cases catch(Exception) may be ok. For example:
try
{
DoSomething();
}
catch (Exception e)
{
LogError(e);
ShowErrorMessage(e); // Show "unexpected error ocurred" error message for user.
}
Because you don't really know why an exception happened, and several exceptions require very special car to be handled correctly (if possible at all), such as a OutOfMemoryException and similar low-level system exceptions.
Therefore, you should only catch exceptions:
which you know exactly how to deal with it (e.g. FileNotFoundException or so)
when you will re-raise them afterwards (for instance to perform post-fail cleanup)
when you need to transport the exception to another thread
I find two acceptable uses of catch(Exception):
At the top level of the application (just before returning to the user). That way you can provide an adequate message.
Using it to mask low-level exceptions as business ones.
The first case is self-explanatory, but let me develop the second:
Doing:
try {
// xxxx
} catch(Exception e) {
logger.error("Error XXX",e)
}
is bug masking like #dimitarvp said.
But the below is different:
try {
// xxxx
} catch(Exception e) {
throw new BusinessException("Error doing operation XXX",e)
}
This way you aren't ignoring bugs and hiding them under the carpet. You are providing a high-level exception with a more explanatory message to higher application layers.
It's also always important to manage exceptions at the correct layer. If you escalate a low-level exception to a high business layer, it's practically impossible for the higher layer to manage it well.
In that case, I prefer to mask the low level exceptions with a business one that provides a better context and message and that also has the original exception to be able to go into the details.
Even so, if you can catch more concrete exceptions and provide better treatment for them you must do it.
If in a block of code you can get an SQLException and a NetworkException you must catch them and provide adequate messages and treatment for each of them.
But if at the end of the try/catch block you have an Exception mapping it to a BusinessException it's ok for me.
In fact, I find it adequate when higher service layers only throw business exceptions (with details inside).
Besides what yet answered by #anthares:
Because when you catch exception you're supposed to handle it properly. And you cannot expect to handle all kind of exceptions in your code. Also when you catch all exceptions, you may get an exception that cannot deal with and prevent code that is upper in the stack to handle it properly.
The general principal is to catch the most specific type you can.
catch(Exception) is a bad practice because it catches all RuntimeException (unchecked exception) too.
This may be java specific:
Sometimes you will need to call methods that throw checked exceptions. If this is in your EJB / business logic layer you have 2 choices - catch them or re-throw them.
Catching specific exception classes means you will need to re-analyze your actions for which exceptions can be thrown when you look to see how this code handles exceptions. You will often get into a "what if..." situation and it can be a lot of effort just working out if exceptions are handled correctly.
Re-throwing means that code calling your EJBs will be littered with catching code that will typically not mean anything to the calling class. n.b. throwing checked exceptions from EJB methods will mean that you are responsible for manually rolling back any transactions.
But sometimes it is OK! Like if you have a piece of code that does something 'extra', which you really don't care about, and you don't want it to blow up your application. For example, I worked on a large application recently where our business partners wanted a certain daily transaction to be summarized in a new log file. They explained that the log wasn't all that important to them, and that it did not qualify as a requirement. It was just something extra that would help them make sense of the data being processed. They did not need it, because they could get the information elsewhere. So that is a rare case where it is perfectly fine to catch and swallow exceptions.
I also worked at a company where all Throwables were caught, and then rethrown inside a custom RuntimeException. I would not recommend this approach, but just pointing out that it is done.
Isn't it another valid scenario to ensure that a thread keeps alive catching exception inside it?
Thread shouldRunWhenApplicationRuns = new Thread() {
#Override
public void run() {
try {
// do something that should never end
} catch (Exception ex) {
// log it
}
};
shouldRunWhenApplicationRuns.start();
Sonar has also a good Explanation, why this is not a good idea, and how it can be prevented:
https://rules.sonarsource.com/java/RSPEC-2221
Catching Exception seems like an efficient way to handle multiple possible exceptions. Unfortunately, it traps all exception types, both checked and runtime exceptions, thereby casting too broad a net. Indeed, was it really the intention of developers to also catch runtime exceptions? To prevent any misunderstanding, if both checked and runtime exceptions are really expected to be caught, they should be explicitly listed in the catch clause.

How would you intercept all Exceptions?

What is according to you the simplest way to intercept all exceptions in a Java application?
Would AOP be needed to provide this kind of functionality or can it be done with dynamic proxies or is there another way?
Is the simplest solution also a good solution regarding impact on execution performance?
I would like to hear possible solutions from more experienced developers as I'm trying to grasp the technical know-how about the subject.
EDIT:
Thanks for the good advice already, but doesn't the current advice only apply to checked exceptions? What about unchecked exceptions, like NullPointerExceptions, wouldn't it be useful if these could be caught and that the application on catching them dumps the heap/stack to provide you with the current context of the application at the moment of crashing?
What is the purpose of you wanting to intercept every exception - for logging, error reporting?
Intercepting every single exception in every single line of a Java program is possible, but would probably incur quite a performance hit. If it's unavoidable, it'd probably be best to use something like AspectJ, which can run at compile-time (i.e. it "weaves" into your class files) and as such is much faster than dynamic proxies.
But it's something I would try to avoid doing at all costs! In general I would say it's better to limit the scope of the exceptions you want to catch. Also you might want to look into Thread.setDefaultUncaughtExceptionHandler, which I find useful for displaying error dialogs in GUI applications.
Similar to Phil's answer, here is some sample code showing how to use the uncaught exception handler. This works for both checked and unchecked exceptions.
Edit: Updated to print the stack trace based on updated comments in the question.
import java.lang.Thread.UncaughtExceptionHandler;
public class Test {
public static void main(String[] args) throws Exception {
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace();
}}
);
// throw new RuntimeException(); /* this works too */
throw new Exception();
}
}
At Nate and Konamiman... What you're suggesting does not work at all and does not answer the OP's question.
What if the OP starts a new thread from inside your try/catch?
For example:
public static void main(String[] args) {
try {
final Thread t = new Thread( new Runnable() {
public void run() {
System.out.println( 3 / Math.min(0,4) );
}
} );
t.start();
catch(Throwable t) {
...
}
}
Then you're not catching the exception.
The correct way to do it is to use Thread.setDefaultUncaughtExceptionHandler.
public static void main(String[] args) {
try {
...
catch(Throwable t) {
...
}
}
More importantly than simply catching all exceptions is WHERE you catch the exception:
Don't catch an exception unless you can do something about it. If you can't do anything about it, either let it bubble up to the next level or catch it, re-wrap it as a more specific exception and re-throw it.
Always have a global exception handling block (like in Nate's answer) to catch any errors you can't handle anywhere so you can fail somewhat gracefully.
If you simply want to catch an Exception, a try/catch block will suffice. If you want to prevent them being thrown or do some logging or wrapping of the Exception, you will probably need some AOP to do this. AspectJ will handle it pretty well, but beware of potential performance bottlenecks.
Dynamic proxies will only work when the method is proxied, so if any Exception is thrown and caught inside the execution of the proxy object there is no means for the proxies to intercept the Exception.
One thing to consider is if you are catching all exceptions, or only checked exceptions. To catch all exceptions, AspectJ's around throwing or after throwing advice would weave some processing around every method, this involves the creation of JoinPoint objects and synthetic methods at every method invocation. This is not normally a problem unless the process is in a tight loop, where the garbage collection can go through the roof.
To all those questionning the need to catch all exceptions...
There are a lot of valid reasons to catch all exceptions:
someone mentionned displaying a dialog in a GUI app telling about the problem
working around bugs in a 3rd party API you really need
working around bugs in some JVM implementation
self-healing software.
automatic online exception reporting.
Note that Java itself does intercept all exceptions on the EDT (Event Dispatch Thread) and spawns a new EDT when the EDT dies. You can consider that a form of "self-healing" software. The EDT dying is not something unheard of and doesn't exactly prevent the applications from running correctly (on the contrary). (and, yup, Swing and AWT have quite some bugs, just take a look at the Sun bug parade ;)
It could be argued that any self-respecting software should actually take into account the case of an unforeseen exception (are all the software you ship 100% bug free and never gets new releases, bug-fix releases?) and do something smart when such unforeseen exception happen.
The 'something smart' may be preventing the software from crashing (like in the EDT case), warning the user, sending a report, etc.
Answers questionning the need to do such a thing or suggesting that doing so is a bad practice should IMHO be modded down.

Why catch Exceptions in Java, when you can catch Throwables?

We recently had a problem with a Java server application where the application was throwing Errors which were not caught because Error is a separate subclass of Throwable and we were only catching Exceptions.
We solved the immediate problem by catching Throwables rather than Exceptions, but this got me thinking as to why you would ever want to catch Exceptions, rather than Throwables, because you would then miss the Errors.
So, why would you want to catch Exceptions, when you can catch Throwables?
From the Java API documentation:
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.
Errors usually are low-level (eg., raised by the virtual machine) and should not be caught by the application since reasonable continuation might not be possible.
It all depends a bit on what you're going to do with an Error once you've caught it. In general, catching Errors probably shouldn't be seen as part of your "normal" exception flow. If you do catch one, you shouldn't be thinking about "carrying on as though nothing has happened", because the JVM (and various libraries) will use Errors as a way of signalling that "something really serious has happened and we need to shut down as soon as possible". In general, it's best to listen to them when they're telling you the end is nigh.
Another issue is that the recoverability or not from an Error may depend on the particular virtual machine, which is something you may or not have control over.
That said, there are a few corner cases where it is safe and/or desirable to catch Errors, or at least certain subclasses:
There are cases where you really do want to stop the normal course of flow: e.g. if you're in a Servlet, you might not want the Servlet runner's default exception handler to announce to the world that you've had an OutOfMemoryError, whether or not you can recover from it.
Occasionally, an Error will be thrown in cases where the JVM can cleanly recover from the cause of the error. For example, if an OutOfMemoryError occurs while attempting to allocate an array, in Hotspot at least, it seems you can safely recover from this. (There are of course other cases where an OutOfMemoryError could be thrown where it isn't safe to try and plough on.)
So the bottom line is: if you do catch Throwable/Error rather than Exception, it should be a well-defined case where you know you're "doing something special".
Edit: Possibly this is obvious, but I forgot to say that in practice, the JVM might not actually invoke your catch clause on an Error. I've definitely seen Hotspot glibly gloss over attempts to catch certain OutOfMemoryErrors and NoClassDefFoundError.
A lot of the other answers are looking at things too narrowly.
As they say, if you are writing application code, you should not catch Throwable. You can't do anything about it, so allowing the surrounding system (JVM or framework) to handle these issues is best.
However, if you are writing "system code", like a framework or other low-level code then you may very well want to catch Throwable. The reason is to attempt to report the exception, perhaps in a log file. In some cases your logging will fail, but in most cases it will succeed and you will have the information you need to resolve the issue. Once you have made your logging attempt you should then either rethrow, kill the current thread, or exit the entire JVM.
Usually Errors are problems you cannot possibly recover from, like OutOfMemoryError. There's nothing to do by catching them, so you should usually let them escape, and bring down the virtual machine.
I'll go a slightly different route from others.
There are many cases where you would want to catch Throwable (mainly to log/report that something evil happened).
However, you need to be careful and rethrow anything that you cannot deal with.
This is especially true of ThreadDeath.
If you ever catch Throwable, be sure to do the following:
try {
...
} catch (SomeExceptionYouCanDoSomethingWith e) {
// handle it
} catch (ThreadDeath t) {
throw t;
} catch (Throwable t) {
// log & rethrow
}
There's at least one case when I think you may have to catch a throwable or a generic exception - if you're running a separate thread to perform a task, you may want to know if the "run" method of the thread has catched some exception or not. In that case, you probably will do something like this:
public void run() {
try {
...
}
catch(Throwable t) {
threadCompletionError = t;
}
}
I am really not sure if it's the best approach, but it works. And I was having a "ClassNotFound" error being raised by the JVM, and it's an error and not an exception. If I let the exception be thrown, I am not sure how to catch it in the calling thread (probably there's a method but I don't know about it - yet).
As for the ThreadDeath method, don't call the "Thread.stop()" method. Call Thread.interrupt and have your thread to check if it was interrupted by someone.
This post won't make the "checked exceptions are bad" people happy. However, what I am basing my answer on is how Java exceptions are intended to be used as defined by the people that created the language.
Quick reference chart:
Throwable - never catch this
Error - indicates a VM error - never catch this
RuntimeException - indicated a programmer error - never catch this
Exception - never catch this
The reason you should not catch Exception is that it catches all of the subclasses, including RuntimeException.
The reason you should not catch Throwable is that it catches all of the subclasses, including Error and Exception.
There are exceptions (no pun intended) to the above "rules":
Code you are working with (from a 3rd party) throws Throwable or Exception
You are running untrusted code that could cause your program to crash if it thew an exception.
For the second one usually it is enough to wrap main, event handling code, and threads with the catch to Throwable and then check the actual type of the exception and deal with it as appropriate.
Do NOT ever catch Throwable or Error and you should generally not simply catch a generic Exception either. Errors are generally things that most reasonable programs cannot possibly recover from. If you know what is going on, you might be able to recover from one specific error, but in that case, you should catch only that one particular error and not all errors in general.
A good reason not to catch Error is because of ThreadDeath. ThreadDeath is a fairly normal occurrence that can theoretically be thrown from anywhere (other processes like the JVM itself can generate it), and the whole point of it is to kill your thread. ThreadDeath is explicitly an Error rather than an Exception because too many people catch all Exceptions. If you ever were to catch ThreadDeath, you must rethrow it so that your thread actually dies.
If you have control over the source, it should probably be restructured to throw an Exception rather than an Error. If you don't, you should probably call to the vendor and complain. Errors should be reserved for only things that are terminal with no possible way to recover from them.
Normally when programming, you should only catch a specific exception (such as IOException). In a lot of programs you can see a very toplevel
try {
...
} catch(Exception e) {
...
}
That catches all errors which could be recoverable and all those which indicate a bug in your code, e.g. InvalidArgumentException, NullPointerException. You can then automatically send an eMail, display a message box or whatever you like, since the JavaVM itself is still working fine.
Everything derived from Error is something very bad, you can't do anything against. The question is, if it makes sense to catch a OutOfMemoryError or a VirtualMachineError. (It is a error in the JavaVM itself, probably you can't even display a message box or send an eMail then)
You should probably not a class derived from Error, you should derive from Exception or RuntimeException.
I know it might be counter-intuitive, but just because you can catch all sorts of Exceptions and Throwables and Errors does not mean you should.
Over-aggressive catching of java.lang.Exception can lead to some serious bugs in applications - because unexpected Exceptions never bubble up, are never caught during development/testing, etc.
Best practice: only catch
Exceptions that you can handle
Exceptions that are necessary to catch
In general it would be reasonable to try to catch Errors if only so that can be properly reported.
However, I believe there are cases when it would be appropriate to catch an Error and not report it. I'm referring to UnsatisfiedLinkError. In JAI the library uses some native libraries to implement most of the operators for performance reasons, however if the library fails to load (doesnt exist, wrong format, unsupported platform) the library will still function because it will fall back into a java only mode.
Slightly off topic, but you may also want to look at this very good article about exceptions.
Why not catch them all? Then log them, at least you know you have an error. So better catch Throwable/s than Exception/s only.
There is no point in catching Error.
Errors are used to indicate something went really wrong in your application and it should be restarted.
For instance one common error is
java.lang.OutOfMemoryError
There is NOTHING you can do when that happens. Is already too late, the JVM has exhausted all its options to get more memory but it is impossible.
See this other answer to understand more about the three kinds of exceptions.

Categories

Resources