How can I catch AWT thread exceptions in Java? - java

We'd like a trace in our application logs of these exceptions - by default Java just outputs them to the console.

Since Java 7, you have to do it differently as the sun.awt.exception.handler hack does not work anymore.
Here is the solution (from Uncaught AWT Exceptions in Java 7).
// Regular Exception
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
// EDT Exception
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
// We are in the event dispatching thread
Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());
}
});

There is a distinction between uncaught exceptions in the EDT and outside the EDT.
Another question has a solution for both but if you want just the EDT portion chewed up...
class AWTExceptionHandler {
public void handle(Throwable t) {
try {
// insert your exception handling code here
// or do nothing to make it go away
} catch (Throwable t) {
// don't let the exception get thrown out, will cause infinite looping!
}
}
public static void registerExceptionHandler() {
System.setProperty('sun.awt.exception.handler', AWTExceptionHandler.class.getName())
}
}

A little addition to shemnons anwer:
The first time an uncaught RuntimeException (or Error) occurs in the EDT it is looking for the property "sun.awt.exception.handler" and tries to load the class associated with the property. EDT needs the Handler class to have a default constructor, otherwise the EDT will not use it.
If you need to bring a bit more dynamics into the handling story you are forced to do this with static operations, because the class is instantiated by the EDT and therefore has no chance to access other resources other than static. Here is the exception handler code from our Swing framework we are using. It was written for Java 1.4 and it worked quite fine there:
public class AwtExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(AwtExceptionHandler.class);
private static List exceptionHandlerList = new LinkedList();
/**
* WARNING: Don't change the signature of this method!
*/
public void handle(Throwable throwable) {
if (exceptionHandlerList.isEmpty()) {
LOGGER.error("Uncatched Throwable detected", throwable);
} else {
delegate(new ExceptionEvent(throwable));
}
}
private void delegate(ExceptionEvent event) {
for (Iterator handlerIterator = exceptionHandlerList.iterator(); handlerIterator.hasNext();) {
IExceptionHandler handler = (IExceptionHandler) handlerIterator.next();
try {
handler.handleException(event);
if (event.isConsumed()) {
break;
}
} catch (Throwable e) {
LOGGER.error("Error while running exception handler: " + handler, e);
}
}
}
public static void addErrorHandler(IExceptionHandler exceptionHandler) {
exceptionHandlerList.add(exceptionHandler);
}
public static void removeErrorHandler(IExceptionHandler exceptionHandler) {
exceptionHandlerList.remove(exceptionHandler);
}
}
Hope it helps.

There are two ways:
/* Install a Thread.UncaughtExceptionHandler on the EDT */
Set a system property:
System.setProperty("sun.awt.exception.handler",MyExceptionHandler.class.getName());
I don't know if the latter works on non-SUN jvms.
--
Indeed, the first is not correct, it's only a mechanism for detecting a crashed thread.

Related

java Catch exception inside a async callback

I have a callback which may throw a custom exception.
I'm trying to throw it, but it's not being catched on the outer scope, nor the compiler let me catch it, it says: "Exception is never thrown is the corresponding try block", even though it is.
this is my code:
public void openAsync(MessageAsyncCallback callback) {
try {
this.sendChannelOpen(this.getChannel(), getChannelOpenData().getFlags(), new MessageAsyncCallback() {
#Override
public void onComplete() throws NanoException {
// INanoPacket message = transport.getMessageByClassName(AudioServerHandshake.class.getName());
INanoPacket message = transport.getMessageByClassName(AudioClientHandshake.class.getName());
Log.info("Got audio server handshake, trying to client-handshake it");
sendClientHandshakeAsync((AudioServerHandshake) message, callback);
}
});
} catch (NanoException e) {
System.exit(-2);
}
}
and it doesn't let me catch NanoException
EDIT:
inside transport.getMessageByClassName I throw a NanoException.
EDIT2:
this is the method who invokes the exception:
public INanoPacket getMessageByClassName(String destClassName) throws NanoException {//} throws NanoException {
long startTime = System.currentTimeMillis(); // fetch starting time
INanoPacket message = this.getMessageFromTCPQueue();
while (!(message.getClass().getName().equals(destClassName)) && isRuntimeValid(startTime)) {
this.insertToTCPQueue(message); // put message back in queue
message = this.getMessageFromTCPQueue();
}
if (!(message.getClass().getName().equals(destClassName))) {
// timeout...
throw new NanoException("Couldn't find destination message: " + destClassName);
}
return message;
}
and I want to handle the exception not even in openAsync but on the method that calls openAsync.
why? because I'm handling messages coming from a remote device, this is why it's async. and I'm using some kind of timeout to wait for a specific message, and if the message isn't coming I want to restart the whole program.
Please notice that in your code you are not invoking onComplete method, you are defining it.
The exception would be thrown in a separate part of the code, possibly separate Thread (as it seems to be async). Therefore the "Exception is never thrown is the corresponding try block" message is right, as the exception will never be thrown when invoking this.sendChannelOpen(...) method.
Your try-catch statement needs to wrap the place where you invoke the onComplete method. As only by invoking onComplete method can you expect NanoException.
EDIT based on comments:
If you need to handle the exception throw in getMessageByClassName you can do it in onComplete method and not rethrow it. If you want to handle it somewhere else, you'd need to provide us the code of sendChannelOpen method or a place where the callback is invoked.
EDIT2 (based on question edits):
Please see the code below, as an example of how you can communicate between threads. I've used Latch, but there are other classes in java.util.concurrent that you may find useful.
BTW, I'm not going into the discussion why you want to restart the whole app on your NanoException, although there might be other options worth considering for recovering from that Exception.
import java.util.concurrent.CountDownLatch;
class NanoException extends Exception {}
interface MessageAsyncCallback {
void onComplete() throws NanoException;
}
public class AsyncApp {
private static final CountDownLatch errorLatch = new CountDownLatch(1);
public static void main(String[] args) {
new AsyncApp().run();
}
void run() {
sendChannelOpen("something", new MessageAsyncCallback() {
#Override
public void onComplete() throws NanoException {
// the whole try-catch-sleep is not really needed, just to wait a bit before exception is thrown
try {
// not needed, just to wait a bit before exception is thrown
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new NanoException();
}
throw new NanoException();
}
});
try {
System.out.println("This is a main thread and we wait here, while the other thread executes...");
errorLatch.await();
System.out.println("Latch has reached 0, will now exit.");
System.exit(-2);
} catch (InterruptedException e) {
System.out.println("Error in main thread.");
System.exit(-1);
}
}
void sendChannelOpen(String notImportant, MessageAsyncCallback troublesomeCallback) {
runSomethingInSeparateThread(troublesomeCallback);
}
void runSomethingInSeparateThread(MessageAsyncCallback troublesomeCallback) {
new Thread(() -> {
try {
troublesomeCallback.onComplete();
} catch (NanoException e) {
System.out.println("You can catch it here, and do system exit here or synchronize with main Thread as below");
errorLatch.countDown();
}
}).start();
}
}

Can I call a method before my application go to crash

I'm a newbie in android and I always see Exception when I'm running my code.
So, somebody can tell me Can I call a method before app go to crash anywhere without "try-catch".
This would be better way to handle uncaught exception:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
appInitialization();
}
private void appInitialization() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
private UncaughtExceptionHandler defaultUEH;
// handler listener
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable ex) {
ex.printStackTrace();
// TODO handle exception here
}
};
}
Application is a Base class for those who need to maintain global application state. And hence here, it will be a better place to handle such exceptions.
EDIT:
The above code will handle uncaught exceptions if they are thrown inside UI thread.
If an exception has occurred in worker thread, you can handle it in following way:
private boolean isUIThread(){
return Looper.getMainLooper().getThread() == Thread.currentThread();
}
// Setup handler for uncaught exceptions.
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
{
#Override
public void uncaughtException (Thread thread, Throwable e)
{
handleUncaughtException (thread, e);
}
});
public void handleUncaughtException(Thread thread, Throwable e) {
e.printStackTrace(); // not all Android versions will print the stack trace automatically
if (isUIThread()) {
// exception occurred from UI thread
invokeSomeActivity();
} else { //handle non UI thread throw uncaught exception
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
invokeSomeActivity();
}
});
}
}
I think what you search is the UncaughtExceptionHandler. It is notified whenever an Exception is fired and not catched on its way bubbling up through your application.
See http://www.intertech.com/Blog/android-handling-the-unexpected/ for more details on implementing this in android.
Try this way
1) create class
import android.content.Context;
import android.content.Intent;
import android.os.Process;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
public class CrashReportHandler implements UncaughtExceptionHandler {
public static void attach(Context context) {
Thread.setDefaultUncaughtExceptionHandler(
new CrashReportHandler(context)
);
}
///////////////////////////////////////////// implementation
private CrashReportHandler(Context context) {
m_context = context;
}
public void uncaughtException(Thread thread, Throwable exception) {
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
//You will get call back here when app crashes.
// from RuntimeInit.crash()
Process.killProcess(Process.myPid());
System.exit(10);
}
private Context m_context;
}
How to use this class?
write this line in your activity onCreate() method
CrashReportHandler.attach(this);
There is method called Uncaught exception which is called just before force close dialog , you can write ur piece of code there .. Please check Using Global Exception Handling on android
Use CrashLytics for crash reporter free of cost and easy to implement
https://www.crashlytics.com/

Efficient exception handling for threads in java

How do we implement efficient exception handling when using threads.
I have a main program which creates 3 threads. How do we handle the exceptions for the exceptions thrown during the execution of thread?
Can we use the try/catch block or uncaughtexception. If so, can you please share some samples.
public class MyThreadTest {
public static void main(String[] args) {
Thread newThread = new Thread(new ThreadWithException());
// Add the handler to the thread object
newThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
#Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("ERROR! An exception occurred in " + t.getName() + ". Cause: " + e.getMessage());
}
});
newThread.start();
}
}
/**
* This thread throws a custom exception in its run method.
*/
class ThreadWithException implements Runnable {
#Override
public void run() {
throw new RuntimeException("Application Specific Exception!!");
}
}
Either you can use:
Thread#setUncaughtExceptionHandler to specify some code that is run when an exception is thrown (outside of normal program flow), or:
ExecutorService#invokeAll to run all of your blocks, and inspect the returned list for Future#get()'s throwing of ExecutionException. Another option is CompletionService, but this is slightly harder to use for such a simple case.
You can use try / catch block strategy:
Thread t = new Thread() {
#Override
public void run() {
try {
//..thread code
} catch (Exception e) {
}
}
};
It is easy to implement but in case of exception main thread of your application will never know what happened inside of child thread.
Better method would be to spawn threads using ExecutorService (as mentioned by FauxFaux). This will allow you to easily pass information about the error to main thread. Besides that, using ExecutorService allows you to write less code. You won't have to manage threads in your code but leave it for ExecutorService instead.
beacuse , recently, I have write a program with about 3 threads in order to fill a lot data from mysql and mongoDb to ElasticSearch. I share u my code.
I use java.util.concurrent.Executors.
First I have a main class. It calls
public void start() throws Exception {
this.logger.info("Main: Start the worker manually");
schedulerThreadPool = Executors.newScheduledThreadPool(this.maxNumberOfThread);
for (int i = 0; i < this.maxNumberOfThread; i++) {
Worker worker = new Worker();
long delay = i * this.sleepBetweenTaskStart;
schedulerThreadPool.scheduleAtFixedRate(worker, delay, this.minTimeBetweenEachTask, TimeUnit.MILLISECONDS);
}
}
And Worker implements Runnable and get Thread Id by below code.
this.threadId = Thread.currentThread().getId();
And just try catch in each Worker. Everything works normally.
#Override
public void run() {
try {
do...
} catch (Exception e) {
e.printStackTrace();
}
}

Catch exceptions in javax.swing application

I'm working with javax.swing to make an aplication which generates forms from XML Schema (using JAXFront library) and stores the data filled by the user them into XML documents.
I have put try-catch-finally blocks when I need it, but I have a little problem catching exceptions when the main thread ends (The AWT threads are still running).
I have two classes which do the main work and other classes which aren't important for the question:
Main class: It has the following structure. Initializes the application and runs the main frame
public class Main {
public static void main(String[] args) {
readArgs(); // An INI file with the app config
Model model = initializeElements(args); // My model class
try {
MyFrame mfr = new MyFrame(title,model);
mfr.visualize(); // Assembling view and setting visible
} catch( Excepion e ) {
doCleanUp();
System.exit(-1);
}
}
}
Frame Class: Generates the view and listen events
public class MyFrame extends JFrame implements ActionListener,MenuListener {
// Some attributes
// Other mthods without importance
/**
* Compose the elements, add listeners and set visible the frame
*/
public void visualize() {
generateFormPanel();
setListeners();
validate();
setVisible(true);
}
public MyFrame(String title, Modele model) {
super(title);
createElementsUsing(model);
}
public void actionPerformed(ActionEvent e) {
// Code to manage events
}
}
Well, the problem is the following:
When the visualize function is exectuted from the main method, the view is generated and showed. At that moment is when I lose the control of the exceptions catching. Then my question is if there are some way to catch the possible RuntimeExceptions throwed after this point.
I hope you understand my English and can answer the question.
Thanks in advance.
Simplest version is to set the default uncaught exception handler:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
// do something
}
});
But that catches uncaught exceptions thrown in other parts of the program aswell.
You could however catch only runtime exceptions thrown off the swing event dispatching thread using a proxy (See this page for more information, copied code from there):
class EventQueueProxy extends EventQueue {
protected void dispatchEvent(AWTEvent newEvent) {
try {
super.dispatchEvent(newEvent);
} catch (Throwable t) {
// do something more useful than: t.printStackTrace();
}
}
}
Now installing it like this:
Toolkit.getDefaultToolkit().getSystemEventQueue().push(new EventQueueProxy());
After you have called visualize() the only thread running is the Swing/AWT event dispatch thread. If you want to catch any exceptions you will need to do so in any of your listener methods that are called on this thread e.g.
public void actionPerformed(ActionEvent e) {
try {
// Some code here
} catch(RuntimeException e) {
// Handling code here
}
}
To prevent boilerplate you can have this code in a super class.
Note that you can also set a default uncaught exception handler if you want to catch anything not already dealt with by the Swing/AWT thread.
Note also that in general it is best practice to not catch subclasses of RuntimeException if you can avoid it.
Try adding:
setDefaultCloseOperation(EXIT_ON_CLOSE);
to MyFrame constructor. Not sure though, but worth trying.

Is there a standard JDK interface which a method like void run() throws Exception?

What I want is a standard JDK class that look like this:
interface ExplodingRunnable {
void run() throws Exception;
}
Callable is no good, because its call() method is required to return a value, but I need a void.
Runnable is no good, because its run() method doesn't declare throws Exception.
I sort of need a combination of the two. Any ideas?
EDIT: I should have mentioned that I tried Callable<Void> but it requires you to define a method:
public Void call() {
// run your code;
return null; // ugly!
}
I'm looking for something a bit nicer.
Why do I want this?
I'm implementing a standard why of catching "will never happen" Exceptions (they will never happen, but various APIs define their methods throwing Exceptions) and throwing any Exceptions that might occur by wrapping them in an (unchecked) RuntimeException, so the caller can simply pass a "ExplodingRunnable" in and not have to code loads of perfunctory try/catch blocks that will never be exercised.
FINAL EDIT It looks like what I was looking for doesn't exist. The accepted answer is the closest to "correct", but it looks like there is no solution to answer the question as asked.
Could you just use Callable<Void>?
An interface with only one method, which returns void and throws Exception.
Among all java and javax classes, only one fits that description:
package java.lang;
public interface AutoCloseable
{
void close() throws Exception;
}
Well... the word "close" has many meanings...
You want to surround a bunch of statements with some extra handling, there is no sin to define your own interface here. You may find that your API requires users to learn 4 new phrases
Util.muckException( new ExplodingRunnable() { public void run() throws Exception
^1 ^2 ^3 ^4
You can actually cut down two, and user code would look like this
new MuckException(){ public void run() throws Exception
{
statement_1;
...
statement_n;
}};
public abstract class MuckException
{
public abstract run() throws Exception;
public MuckException()
{
try{ run(); }
catch(Exception e){ throw new Error(e); }
}
}
Just use Callable, ignore the return value and document things as ignoring the returned value and recommend returning null. Just because you can return something does not mean you have to.
I would just use Callable<Void> and learn to love it. ;)
You can have the checked exception not declared with the following.
Runnable runs = new Runnable() {
public void run() {
try {
// do something
} catch(Exception e) {
// rethrows anything without the compiler knowing.
// the method is deprecated but can be used on the current thread.
Thread.currentThread().stop(e);
}
}
});
Future future = executorService.submit(run);
try {
future.get();
} catch (ExecutionException ee) {
Throwable e = ee.getCause(); // can be the checked exception above.
}
and not have to code loads of perfunctory try/catch blocks that will never be exercised.
I had the same issue and fixed it a little differently
// Exceptions class
public RuntimeException wrap(Exception e) {
return e instanceof RuntimeException ? ((RuntimeException)e) : new RuntimeException(e);
}
// user code
try {
foo.bar();
} catch (Exception e) {
throw Exceptions.wrap(e);
}

Categories

Resources