简体   繁体   中英

Java : Catch exception in different thread

I'm developing a Swing application that also does use a REST-API. I'm using Jersey to accomplish this.

I want the user to input a URL into a TextField and would like to give him some feedback if the URL is malformed or anything. I'm using URI as a basis to store the URL and am able to catch any problems that arise with that and give the user some informations.

 } catch (URISyntaxException ex) {
        MainClass.write2Log("URL wrong : '" + baseURL + "'");
        }

Now, when the URL has the right format, but simply doesn't resolve, I get this exception :

Exception in thread "AWT-EventQueue-0" javax.ws.rs.ProcessingException:
java.net.UnknownHostException: sx.dddsds.ded
at org.glassfish.jersey.client.HttpUrlConnector.
apply(HttpUrlConnector.java:205)

So my questions is this : How can I 'catch' this exception when I don't have the Object that throws this exception?

Thanks in advance !

Exceptions travel up the call stack on the thread they were thrown in; they don't cross threads. If you want to catch an exception, you need your try-catch block somewhere in the stack trace that you didn't post in your question.

Looking at the lines you did post, it's looking like you're trying to execute a long-running operation (an HTTP request) on the event thread; it should be running somewhere else.

You can set it for particullar (for example current, or any other Thread instance) thread or globally for all uncaught exceptions:

Thread.setDefaultUncaughtExceptionHandler( ... );
Thread.currentThread().setUncaughtExceptionHandler( ...);

Starting a new thread by Thread you can set exception handler, and if you start new thread with executor you can set your custom thread factory, that will set exception handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM