Uncaught exception within uncaught exception handler - java

This question may sound a little silly ;)
How would approach the possibility of an uncaught exception within the UncaughtExceptionHandler?

Very interesting question, I haven't thought about this before.
The approch seems to be that either set your own uncaughtExceptionHandler on your thread or it will get passed to JAVAs defaultUncaughtExceptionHandler,
I made some quick googeling and found a similar case for getting crash data from android.
I think you may be intresing in this link How do I obtain crash-data from my Android application?

Well, you have to catch them yourself. The documentation of uncaughtException() linked by you states this clearly:
Any exception thrown by this method will be ignored by the Java Virtual Machine.
But you can only plan so far. So you handle the exceptions of your exception handler but who handles that code? It's the same with logging a failed logging event. Exception handlers all the way down...

Related

Getting UndeclaredThrowableException in a Thrift call

I am getting this
java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy1.getMyObject(Unknown Source)
I went through a similar post here and this article posted in one the comments .
But in this case the I am calling following method using a ThriftClient which was created using com.twitter.common.thrift.ThriftFactory<T>
myThriftClient.getMyObject()
Is there any way of knowing what is the actual cause of this error ? Should I need to change something in thrift side code ?
It does not seem like this is a Thrift issue at all... it seems like it is inside the library that you are using ("twitter commons" or whatever). I presume that their library is trying to create a dynamic proxy for your interface, but your interface it unable to handle whatever checked exception is being thrown.
You might want to try declaring "throws java.lang.Throwable" on your interface temporarily if you are having trouble ascertaining the underlying exception and are unable to fix the implementation of the Invocation Handler itself. At least the root cause won't be buried by the UndeclaredThrowableException if you do that.
Alternatively, just set a breakpoint in a graphical debugger and step through the invocation to be able to see your program's state.
The issue here was that my client side thread was sending a Thread.interrupt() to the myThriftClient thread.
So in that case the Caller class (which in my case was DeadlineCaller) inside the Thrift class was interrupted which resulted in an InterruptedException or a TimeoutException which was bundled and displayed as UndeclaredThrowableEception in the stack.

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 Propagating Exceptions

When would you want to propagate an exception to another Class/Method versus catching the Exception in the same Class/Method?
You catch the exception where you have to handle it.
As a rule of thumb, you should let your exceptions bubble up, but if you don't want your subroutine to crash due to a (possibly expected) error, than you handle the exception, which normally involves logging an error and/or displaying an error message to the user.
The good practice is "throw early and catch late". That allows you to better understand the cause of the exception.
This topic is fairly broad; fortunately there are good resources already in place:
Guidelines on Exception propagation (in Java)
http://www.javacodegeeks.com/2012/04/exception-handling-guidelines-best.html
Best practices for exception management in Java or C#
The great majority of exceptions occuring in real-life code are not recoverable in the sense there's any meaningful code that will retry the operation or try to do it differently. The only recovery happening is aborting the current unit of work in an orderly manner—logging the exception, releasing any resources and similar.
This means that, as a first rule, you'll always want to propagate the exception towards that well-defined exception barrier that demarcates your unit of work.
If your code demands anything different than this, it is probably going to be obvious enough, so you don't need to think about it in the general.

Question about Java.lang.Error

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.

Global Exception Handlers in Java

I am thinking of setting up a global, default Exception handler for my (Android) Mobile application(which uses Java syntax) using Thread.setDefaultUncaughtExceptionHandler(...) call. I am thinking of just displaying an Alert Dialog with appropriate message to the user.
Are there any gotchas, caveats and rules that one needs to follow when setting DefaultExceptionHandlers? Any best practices like making sure that the process is killed, full stack trace is written to logs etc. ?
Links to documentation, tutorials etc. that can throw some light on this are welcome.
Thanks.
The name is a bit misleading, because using that method will set a default exception handler for all threads.
Make sure no exceptions can be thrown from your exception handler.
If you're doing GUI stuff from your exception handler, make sure you're doing it from the right thread.
An uncaught exception will only stop the thread where the exception took place, if that also causes the process to terminate depends on any other threads that might be running.
One possible problem with creating a global exception handler is you may get stuck in a loop of exceptions - some exceptions will be thrown repeatedly unless a program is terminated.
If you mean that when an exception is thrown, a message is displayed then the app is terminated, then you'll be fine.

Categories

Resources