How to catch ExceptionInInitializerError? - java

I want to install some kind of global handler to catch any ExceptionInInitializerError which could be thrown from any static block when some class is loading. Currently it dumps a stack trace to the stderr and exits the application. I want to log a stack trace using my logging framework, then exit the application. Is it possible?

It looks like Thread.UncaughtExceptionHandler is what you are looking.
This answer will provide you with more information.
In essence you need to install default exception handler as soon as possible:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof ExceptionInInitializerError) {
// do something with you're exception
// and than close application
System.exit(-1); // passing
}
}
});

Maybe you can make a global exception handler and just filter your exception out of it.
Example
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof ExceptionInInitializerError) {
//Your handler code
}
}
});

Related

Java - listen when an exception is caught in an external class

Is there a way to create a listener in a separate class that runs a certain piece of code whenever an exception is caught within your project?
My code has a lot of try-catches in it, and if an exception is caught I would like to see the logs using log4j. I can do the following for every try-catch I have fairly easily (just with some time effort):
private static final Logger logger = LogManager.getLogger(Example.class);
public void testMethod() {
try {
// some code here that could throw an exception
} catch(Exception e) {
logger.error("Unexpected error has occurred: ", e);
}
}
This will log the exception using log4j. However, I would need to do that over 50 times, and it's so redundant that I would rather be able to use 1 method to do that. So, is there a way to instead do something like this?
public class ListenerClass {
private static final Logger logger = LogManager.getLogger(ListenerClass.class);
// This method will be listening for exceptions to be caught within the project
/**
* #param e - The exception that was just caught
*/
public void listenerMethod(ExceptionCaught e) {
logger.error("An exception has been thrown: ", e);
}
}
Is this possible?
Thanks
Standard java way:
Thread.setDefaultUncaughtExceptionHandler( (thread, throwable) -> {
log(throwable.getMessage(), thread.getId());
});
which will handle uncaught RuntimeExceptions, and unless otherwise specified it will act for all your application threads.
Just remember the Exceptions are thrown for a reason, and shouldn't be ignored, especially RuntimeExceptions.
If you are using an older version of java (before 8), you must explicitly instantiate an anonymous class:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(final Thread t, final Throwable e) {
}
});
Look at Thread.setDefaultUncaughtExceptionHandler()

GWT - Unable to catch StatusCodeException with UncaughtExceptionHandler

When Tomcat session times out, I want to redirect my user to the homepage of my GWT app, so that they can login again. To force this, I'm trying to use the StatusCodeException thrown by GWT when the user tries to perform any operation after their session times out -
SEVERE: com.google.gwt.user.client.rpc.StatusCodeException: 0
To achieve this, I'm using the following code -
public void onModuleLoad() {
GWT.UncaughtExceptionHandler uncaughtExceptionHandler = new GWT.UncaughtExceptionHandler() {
public void onUncaughtException(Throwable e) {
if (e instanceof StatusCodeException) {
logger.log(Level.ERROR, "Exception caught!");
logger.log(Level.ERROR, ((StatusCodeException) e).getStatusCode());
}
}
};
GWT.setUncaughtExceptionHandler(uncaughtExceptionHandler);
try {
// rest of the code in onModule() - I'm expecting any operation to throw StatusCodeException when session times out.
} catch (RuntimeException ex) {
uncaughtExceptionHandler.onUncaughtException(ex);
}
}
This is not working. Instead of getting caught by the code, the StatusCodeException is being displayed on the console. What am I doing wrong here?
The idea is to catch StatusCodeException and use its getStatusCode() method to find out if the HTTP error code is 403. If it is, I want to use Window.Location.assign("https://example.com/redirect"); to redirect them to a login page.
onFailure(Throwable caught) {
logger.error(caught);
}
Your AsyncCallback.onFailure is doing exactly what you asked it to do - it is logging the error, but not throwing it. Since it wasn't thrown, the uncaught exception handler doesn't handle it (it can't be not-caught, if it wasn't thrown... if that makes sense).
One option could be that you could populate the method with throw caught, but java won't like this. Instead, the easiest answer to your specific on is simply to pass it to the handler:
onFailure(Throwable caught) {
GWT.getUncaughtExceptionHandler().onUncaughtException(ex);
}
One other option you have: since no AsyncCallback will ever throw this, putting the StatusCodeException in the UncaughtExceptionHandler seems a bit odd. Instead, consider making your own AsyncCallback base class, something like this:
public abstract class NetworkAsyncCallback<T> implements AsyncCallback<T> {
#Override
public void onFailure(Throwable t) {
if (e instanceof StatusCodeException) {
logger.log(Level.ERROR, "Exception caught!");
logger.log(Level.ERROR, ((StatusCodeException) e).getStatusCode());
}
}
}
Now, when you make a call, you just have to pass in a new NetworkAsyncCallback<T> and only implement onSuccess. You can skip onFailure if all it was going to do was pass the exceptions to the uncaught handler. Or, if you have some other logic, you can override onFailure, handle the appropriate exceptions, and call super.onFailure(caught) with any other errors so that the superclass handles it.
myServer.getSomeData(param, new NetworkAsyncCallback<Result>() {
#Override
public void onSuccess(Result result) {
//...
}
// Skip onFailure, or if you need custom logic, implement it,
// and call super only if the exception isn't part of that logic
});

How to force normal crash behavior when using setDefaultUncaughtExceptionHandler()?

In an app I'm developing, I'm using Google Analytics to track uncaught exceptions like so:
// ...after setting up Google Analytics...
Thread.setDefaultUncaughtExceptionHandler(new AnalyticsExceptionHandler(Thread.getDefaultUncaughtExceptionHandler()));
And this is the handler, the AnalyticsExceptionHandler class:
public class AnalyticsExceptionHandler implements UncaughtExceptionHandler
{
// Private
private UncaughtExceptionHandler _defaultHandlerRef;
public AnalyticsExceptionHandler(UncaughtExceptionHandler defaultHandlerRef)
{
this._defaultHandlerRef = defaultHandlerRef;
}
#Override
public void uncaughtException(Thread t, Throwable e)
{
// ...track and send the exception to Google Analytics...
_defaultHandlerRef.uncaughtException(t, e);
}
}
Thing is, the app never actually crashes, it just freezes. If I remove the setDefaultUncaughtExceptionHandler() line then the app crashes normally.
Am I doing something wrong in the above code by passing it to the previous default handler?
Why not re-throw the exception?
public void uncaughtException(Thread t, Throwable e)
{
// ...track and send the exception to Google Analytics...
_defaultHandlerRef.uncaughtException(t, e);
throw e;
}

Catch EDT exceptions in a NetBeans environment

I want to catch all uncaught exceptions and bring up a dialog. First I removed the default exception handler from NetBeans and added my handler as default handler:
java.util.logging.Logger global = java.util.logging.Logger.getLogger("");
for (Handler handler : global.getHandlers()) {
if (handler.getClass().getName().equals("org.netbeans.core.startup.TopLogging$LookupDel"))
{
global.removeHandler(handler);
break;
}
}
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
The handler looks like this:
public static final class ExceptionHandler implements UncaughtExceptionHandler
{
#Override
public void uncaughtException(Thread thread, Throwable throwable)
{
logger.error(throwable.getMessage(), throwable);
ExceptionViewPanel.showException(throwable);
}
}
With that construct, I can only catch exceptions which are thrown outside the EDT. I've read about ThreadGroups, but I can't use that solution due we use NetBeans with Maven and so I can't wrap the start thread with a ThreadGroup. The hack from pre-1.7 is also no longer possible and overwriting the EventQueue has no effect.
I've tried many solutions, none of them worked. Does anyone has another solution for me that might work?
Thanks in advance
Teazl
In my own project I've superseded NetBeans error handler to my own. My example:
#ServiceProvider(service = Handler.class, supersedes = "org.netbeans.core.NbErrorManager")
public class MyHandler extends Handler {
#Override
public void publish(LogRecord record) {
if (record.getThrown() != null) {
record.getThrown(); // do with it something
}
}
#Override
public void flush() {
}
#Override
public void close() throws SecurityException {
}
}
See also org.netbeans.core.NbErrorManager and org.netbeans.core.NotifyExcPanel to know how NetBeans uses default handler.
You only need to add this class in your project.

Java thread trobleshooting for SwingWorker like tasks

Thread dump contains wealth of information. For example, if I suspect some action fired more than once, then all I need to do is dumping stack trace each time the action is fired, then investigate the stacks for erroneous action firing.
In certain situations developers are encouraged to abandon conceptual simplicity of sequential execution. For example, Swing offers SwingWorker helper to work around limitations of single threaded EDT. Now, if I dump stack trace, it is useless, because the action is fired by SwingWorker, and there is no information on who initiated SwingWorker task.
So, how do I troubleshoot? Is there a clever trick of "redirecting" thread dump to follow the genuine cause?
You can extend SwingWorker to record the stack when it is created (or when execute but then you need to create another execute method since it is final). Creating the cause is relative expensive though so you might want to do it only when debug (check log level or some such)
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
public abstract class TracedSwingWorker<T, V> extends SwingWorker<T, V> {
private final Exception cause;
public TracedSwingWorker() {
super();
this.cause = new Exception("TracedSwingWorker created at:");
}
#Override
protected final T doInBackground() throws Exception {
try {
return doWorkInBackground();
}
catch(Exception e) {
if(this.cause != null) {
Throwable cause = e;
while(cause.getCause() != null) {
cause = cause.getCause();
}
cause.initCause(this.cause);
}
throw e;
}
}
protected abstract T doWorkInBackground();
// just for testing
public static void main(String[] args) {
new TracedSwingWorker<Void, Void>() {
#Override
protected Void doWorkInBackground() {
throw new IllegalArgumentException("Exception in TracedSwingWorker!");
}
#Override
protected void done() {
try {
get();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
}
}.execute();
}
}
prints:
java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException: Exception in SwingWorker!
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
<snip>
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.Exception: SwingWorker created at:
at TracedSwingWorker.<init>(TracedSwingWorker.java:15)
at TracedSwingWorker$2.<init>(TracedSwingWorker.java:60)
at TracedSwingWorker.main(TracedSwingWorker.java:60)
I might be telling you something you already know but I suggest ThreadDump
http://www.oracle.com/technetwork/java/javase/tooldescr-136044.html#gbmpn
If you use IDE, then this is good:
NetBeans
http://netbeans.org/kb/docs/java/debug-multithreaded.html
I used Eclipse for this a lot. Debugger view has means of visualizing and tracking multiple threads, printing stack and pausing them.

Categories