Question about Java.lang.Error - java

There are lot of posts on java.lang.Error saying it should not be caught. My question is if it should not be caugth the what is the use of it. Since it is Throwable so we can catch it in try catch. I read some posts like only in some situation it should be caught, how to know these situations.
In short i want to know what can go wrong when i catch Error. What is process behind it. Why they have made Error and its Subclasses? If my app is not supposed to catch them then what catches them? Why my code cannot handle this caught Error? If i simply catch one Error and write some handling code in Catch block, won't that code run?

An Error (especially a subclass of VirtualMachineError) indicates that the JVM has encountered an internal issue - one that means that its internal state may no longer be consistent. If you catch an Error and attempt to recover, future behaviour is undefined. The reason that errors are Throwable is so they can be thrown - eg you may do it your self for errors in a native library that can't be recovered from (eg the library could have written to JVM memory, or corrupted its internal static state). The same stack walking and stack trace producing machinery is used in the case of all Throwables - it would be silly to have another mechanism to do the same thing.
Most errors in the JVM that are not VirtualMachineErrors are situations where a native library could have corrupted its static state - eg AWTError, ZipError.
However there are some rare cases where catching an Error is sane: AssertionError in a testing framework, and LinkageError where you have to deal with the absence / presence of different versions of libraries at runtime. This is a pretty rare requirement and may be better handled through reflection.

All rules have exceptions (except this one).
Even if everybody say you should not, there are plenty of cases where it's totally appropriate to catch those java.lang.Error. The logic behind the rule was: "do not try to continue running your application after a fatal condition was detected". You therefore must be careful before doing something after such an error is thrown. It is possible that the system might not be able to continue its task afterward.
It might be OK for a servlet to catch OutOfMemoryError, log the error and destroy the session. Maybe the problem was with that precise session. Destroying it would restore the memory and allow other users to continue using the system. However, you should have a mechanism to track those errors in real-time in order to:
Fix programming errors
(AssertionError, StackOverflowError)
Fix configuration errors
(UnsatisfiedLinkError)
Correct JVM sizing parameters (OutOfMemoryError)
This kind of handling should be done very "high" in the call stack (i.e. near the main()), where the main loop (or equivalent) is performed. I think it's not a good practice to catch Error in deep code, you should at least rethrow the error in those cases.

Similar question already answered here - When to catch java.lang.Error?
Basically, you should never attempt to catch it as its thrown on fairly serious issues like when your thread has dead for some reason, and is not recoverable.
There are however sometimes the need to catch the error when dealing with the framework itself as stated in the above URL.

Related

What does mean by recoverable and un-recoverable exception or error

I'm trying to understand difference between error and exception but it looks same thing and on Oracle Official tutorials I read this line.
Checked exceptions are subject to the Catch or Specify Requirement.
All exceptions are checked exceptions, except for those indicated by
Error, RuntimeException, and their subclasses.
Now about I'm thinking it's same. But after searching more I found some difference as theoretical that.
Exception: are recoverable
Errors: not recoverable.
Exception Example:
try{
read file
}
catch(FileNotFoundException e){
// how I can recover here? can i create that file?
// I think we can just make log file to continue or exit.
}
Error Example:
try{
try to locate memory
}
catch(MemoryError e){
// I think we can just make log file to continue or exit.
}
Edited
I'm asking about recover-able and non-recoverable.
Error, as you already figured out, means you are in serious trouble. In a catch block you might be able to do something like logging, but basically that's it.
Non-recoverable exceptions are mostly runtime exceptions like NullPointerException. They are usually the result of some missed checks in the program code. Therefore the solution is normally to fix the code.
A recoverable exception is something that you know beforehand can happen and take certain measures. Think of a web application that calls some backend service. That service may or may not be available which can cause the execution of the operation to fail. Therefore you have a checked exception, in this case most likely a custom exception that you throw, and then handle it in the front end code in a manner where you tell the user, sorry backend service xy is down, try again later or contact support.
Recoverable does not mean that the application can do something to resolve the cause of the exception, though there may be cases where this is possible.
All classes that inherit from class Exception but not directly or indirectly from class RuntimeException are considered to be checked exceptions.Such exceptions are typically caused by conditions that are not under the control of the program.
Example
in file processing, the program can’t open a file if it does not
exist.
Recoverable
So It is very easy to know that if a file does not exists so you dont need to open that file hence that is recoverable
All exception types that are direct or indirect subclasses of RuntimeException (package java.lang) are unchecked exceptions. These are typically caused by defects in program’s code.
Example
ArrayIndexOutOfBoundsExceptions
ArithmeticExceptions
Error
Unrecoverable
So thatswhy program can not recover from these kind of errors or exceptions
Unrecoverable errors are the ones that put the application in an undefined state, like a broken database connection or a closed port, you may handle the error and continue to execute but it would not make sense. Modern languages like Rust and Go use the name panic for errors of these nature, to make the distinction clear. Best action to take is logging the error, if it is possible, and exiting the application.
A recoverable errors are the ones we can handle gracefully, like division by zero or validation errors. It is something expected and the resulting behavior is covered in the language spec. Yes, application behaves erratic when that a recoverable error happens but we can contain it or work around it.
The Object Throwable has 2 childs : Exception and Error.
All Exceptions are recoverable and all Errors are non-recoverable.
All Exceptions are recoverable because you can catch them and let your program continue its execution.
However all Errors , even when you add them to a catch block, will cause the abrupt termination of your program.
Examples of Errors: StackOverflowError, OutOfMemoryError,..
Remark : Checked and unchecked Exceptions are childs of Exception so recoverable.

What can happen if I catch an error?

Surprisingly google didn't describe any catastrophic scenarios my twisted mind craved for.
Anywhere I read, catching errors is discouraged. Basic rule seems to be that if your application produced error, it's already dead, beyond saving. So if you catch errors in your main function, does your program turn into zombie?
How can even error be caught if the program is already collapsing? Can catching errors do something real bad? Which errors are worst and which are sometimes caught? Could you describe a little test case that can produce the errors (like really produce them, not just throw them) so that I can see that they do if I catch them and ignore them?
Not much happens except that the thrown object is caught. Your process can be in a bad place, though, depending on what caused the error.
A StackOverflowError is pretty undramatic to catch - it's thrown when the maximum stack depth is exceeded, and since it then starts popping the call stack, it's no longer a problem (unless you try calling the offending method again).
class SO {
static int stackOverflow(){ return stackOverflow(); }
public static void main(String... args) {
try {
stackOverflow();
} catch (StackOverflowError e) {
System.out.println("Oh well, life goes on.");
}
}
}
Other errors, like OutOfMemoryError, are somewhat more problematic - there will still be too much memory used after it's been thrown. Some are directly fatal, like ClassFormatError, which means that you're trying to load a broken class file (and it's usually thrown in places where you can't catch it).
Other Errors are somewhere inbetween. AssertionError, for example, is thrown when a programmer-defined condition (like assert answer == 42;) isn't met, but only if you've enabled assertions.
Long story short, though: If you're catching specific errors, you're probably doing the wrong thing (unless you really know what you're doing!). If you're running a server app and want it to keep running, you're probably better of letting the current thread or process die and have it restarted by some kind of monitor.
Catching an Exception or Error is not a good idea, unless;
you can do something useful with it.
as a last resort to ensure it is logged correctly or in a submitted Runnable to an ExecutorService. In this case catching Throwable may be desirable.
Nothing terrible will happen if you catch an Error, however you can't pretend it didn't happen either (i.e. you can't just continue as if it didn't matter)
Note: not catching an error can be a bad thing for multi-threaded applications. This is because an uncaught error only closes the current thread. If there are multiple threads, they will keep running if at least one is not a daemon This can leave a program running but in a bad state.
I ask what happens.
Nothing special, you catch it and you can deal with it or log it.
Are you talking about catching Exceptions? There are two types of Exceptions checked and unchecked. The reason to catch an Exception as simple as catching a programmer defined Exception which enables the user to reenter the data. This normally applies to checked Exceptions.
Unchecked Exceptions cannot be recovered from and you might ask why catch them at all? Perhaps the developer wants to catch it to log the conditions which caused the Exception and to better troubleshoot the issue.
Here is an article discussing them both.
http://tutorials.jenkov.com/java-exception-handling/checked-or-unchecked-exceptions.html

Is it possible to handle all Errors in Java?

I know that Error is Throwable (so it can be handled) and Error handling isn't best practice but suppose we have a requirement to catch all Error.
It is possible in general? I mean what about Errors which can appear in daemon threads? They will crash jvm and I won't know about it.
And can I miss Error even if I surround main(String... args) with try-catch?
You can catch the uncaught exceptions via Thread.setUncaughtExceptionHandler()
Set the default handler invoked when a thread abruptly terminates due
to an uncaught exception, and no other handler has been defined for
that thread.
Uncaught exception handling is controlled first by the thread, then by
the thread's ThreadGroup object and finally by the default uncaught
exception handler. If the thread does not have an explicit uncaught
exception handler set, and the thread's thread group (including parent
thread groups) does not specialize its uncaughtException method, then
the default handler's uncaughtException method will be invoked.
Whether that's a good idea is another question (!). It may be that you simply want to clear up resources, shut down connections etc., log the issue and/or alert the user. If you do have critical issues like OutOfMemoryErrors then there's little else you can do.
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
Now, since Error does indeed extends Throwable, it is possible to catch 'any' error via a simple try-catch statement as follows:
try{
//Error causing code here...
}catch(Error e){
//Handle error here...
}
However, since errors come in different forms, a thrown error may or may not be accompanied by a change in the jvm's behaviour to cause unexpected results.
Consider the Error OutOfMemoryError. When this Error is thrown, the JVM's heap may be so full that any type of handling code results in another OutOfMemoryError being thrown, voiding any attempt of recovery.
Furthermore, even when running on the "primary" thread (the one the application starts in), a error could cause a JVM to crash before every throwing a Error.
Looking at the description of VirtualMachineError (of which Errors such as OutOfMemoryError, StackOverflowError, InternalError, etc are subclasses of) we see:
Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
The javadoc itself states that the jvm no longer can continue operation normally much less allow a programmer to just 'handle' them away.
On the other hand, errors such as UnsatisfiedLinkError generally do not cause a problem with the jvm straight away and can generally be handled (whether this is good practice is debatable). I personally have once used a structure that involves handling a UnsatisfiedLinkError to determine the correct library to load for JNI.
Now, can all errors be handled? Theoretically yes, if we assume that the JVM can continue operation perfectly despite claiming to have failed fatally... With that in regard, practically only a small subset of errors are handleable. Whether or not these small subset of errors should be handled is also a highly controversial topic.
You can handle exceptions, but you can't handle errors.

Java Error handling - is it better to throw Exceptions to centralized error handlers?

I've got a decently complex little game going on in Java (solitaire, essentially like the Windows version), but I have yet to do very much error handling.
Almost all of the methods across my classes will end up either getting called by an initial constructor (eventually main()), a paintComponent() method, or a mouse event. So, my question is, is it bad practice to just use "throws Exception" on all of my lower-level methods, and only do a try/catch at my top-level methods to catch ALL the errors at once? (e.g. 3 try/catches - one for the painting, one for mouse events, one for the main method).
I realize this prevents me from easily dealing with errors on-the-spot, but I don't really plan on doing that anyways. My error handling is going to consist of writing to a log, telling the user, and killing the program. Keeping this in mind, is there anything bad with doing my error handling this way?
It depends on how you want to approach the situation.
If you just want to catch any possible exception and you don't mind about the handler code, you could simply use "throws exception", and there's nothing BAD with it either. It's like a try-catch block that covers all the function.
If you want to write specific code for specific exceptions, you should use try-catch blocks to write appropriate code for each handler.
Based on what you're saying, any caught exception would just notify the user and exit the application. Well, in this case you could just use the first approach. It's not necessarily the BEST approach, and neither is killing the application, however, if that's your strategy you could just use "throws" for each function.
Hope that helps!
If that's all you wan't to do in a case of an error, then it makes perfect sense to do it that way. This eliminates code duplication and scattering of related code. However, if you're thinking of changing how things work in the future (if there's a possibility of this happening), I would suggest to try and push the catch down as far as possible (maybe even eliminating the need for exceptions at all and just logging and exiting right away).
If you use the exception's inner fields (specifically message, which you can set in construction time), you can even eliminate the need for 3 different catch blocks and just use one (depending on your actual actions in case of an error, of course).
I wouldn't - the big reason being that it breaks encapsulation. The reason why this is important in this case is that your error handling code has one of two futures:
Becoming enormous to handle in an informative way every error the program can throw.
Be tiny but not helpful at all: "Some error occurred somewhere".
To my mind, the best structure is to catch the error, log it, alert the user, and exit as far down as possible. There's nothing that says your mouse handling code can't exit, right?
In fact, I would create an error handler class that you can call from just about anywhere, and it handles the notification and logging. Then your exception handlers can just populate it with the message to display/log, and all other code is shared. It will cost you less typing to delegate to this class than adding throws Exception at the end of every function everywhere.
If you must have a top level handler, it should just catch any unexpected runtime errors, so that you can log it and show the user that the program is really quitting for an error, and not just dump to the desktop. All other errors - even if you just want to bail out - should be caught as close to "where the exception has meaning" as possible.
I do the same thing as you are describing most of the time. What you're basically doing is working around the stupid checked exceptions that Java has. It shouldn't even be necessary to add 'throws Exception' everywhere.
If I'm working on an API that other users will use I may create specific exceptions to show what is going on in case they want to handle different exceptions in different ways.
If an error is severe enough to always exit the program, you may be better of throwing a RuntimeException instead. They are used to indicate unrecoverable errors and will avoid problems with putting "throws Exception" everywhere. You should have a handler for RuntimeExceptions anyway to provide a user-friendly error report in case they happen.
If you throw checked exceptions, they should be as specific as possible. Throwing and catching Exception can hide other exceptions that are thrown (including RuntimeExceptions) that you didn't intend and could have been handled differently. If you want to throw a general exception, you can always create your own exception class and throw that instead.
The exception handling can depend on the context so there's not one way to handle everything. If the user clicks a button to open a file and there's an error reading it, then it would be ok to throw an IOException up to the UI layer and display an error message there. On the other hand, an IOException while creating a temporary file could be handled lower down by retrying in another directory.

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