如何捕获Java中另一个线程抛出的异常?

yue*_*r85 4 java multithreading exception-handling

我正在使用一个创建自己的线程的库,它会抛出异常.我怎么能抓住那个例外?在下面标记的行上抛出异常:

ResourceDescriptor rd = new ResourceDescriptor();
        rd.setWsType(ResourceDescriptor.TYPE_FOLDER);
        fullUri += "/" + token;
        System.out.println(fullUri);
        // >>> EXCEPTION THROWN ON THE FOLLOWING LINE <<<
        rd.setUriString(fullUri.replaceAll("_", ""));
        try{
            rd = server.getWSClient().get(rd, null);
        }catch(Exception e){
            if(e.getMessage().contains("resource was not found")){
                this.addFolder(fullUri, label, false);
                System.out.println("Folder does not exist, will be added now.");
            }else{
                System.out.println("Error Messages: " + e.getMessage());
            }
        }
Run Code Online (Sandbox Code Playgroud)

Ort*_*ier 17

如果你无法抓住它可能会帮助你:

如果您有Thread对象,则可以尝试设置UncaughtExceptionHandler.看一下Thread.setUncaughtExceptionHandler(...).

向我们提供有关您使用的库以及如何使用它的更多详细信息.

  • +1我不知道这个.这比我的回答要好. (3认同)

Gra*_*ray 5

如果您拥有的只是一个Thread对象,那么就无法捕获任何异常(我假设是这样RuntimeException).执行此操作的正确方法是Future<?>使用由ExecutorService您使用的类,但您无法控制开始Thread我假设的代码.

如果您要提供Runnable或者如果您将任何代码注入到库中,那么您可以将其包装在一个捕获并保存该类的类中,Exception但这只是在您的代码中存在异常或者在代码中抛出异常时你在打电话.类似于以下内容:

final AtomicReference<Exception> exception = new AtomicReference<Exception>();
Thread thread = library.someMethod(new Runnable() {
   public void run() {
      try {
         // call a bunch of code that might throw
      } catch (Exception e) {
         // store our exception thrown by the inner thread
         exception.set(e);
      }
   }
});
// we assume the library starts the thread
// wait for the thread to finish somehow, maybe call library.join()
thread.join();
if (exception.get() != null) {
   throw exception.get();
}
Run Code Online (Sandbox Code Playgroud)

另外,正如@Ortwin所提到的,如果你要分支你自己的线程,你也可以设置未捕获的异常处理程序:

thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
   public void uncaughtException(Thread t, Throwable e) {
      // log it, dump it to the console, or ...
   }
});
Run Code Online (Sandbox Code Playgroud)

但是,如果库中的线程代码无法被您包装,那么这将无效.如果您编辑问题并显示一些代码并提供更多详细信息,我可以编辑我的问题以提供更好的帮助.