7

我正在使用一个创建自己的线程并引发异常的库。我怎样才能捕捉到那个异常?在下面标记的行上引发异常:

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());
            }
        }
4

2 回答 2

21

如果你不能抓住它,也许这对你有帮助:

如果你有这个Thread对象,你可以尝试设置一个UncaughtExceptionHandler。看看Thread.setUncaughtExceptionHandler(...)

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

于 2012-04-27T14:19:12.003 回答
7

如果你只有一个Thread对象,那么就没有办法捕捉任何异常(我假设是RuntimeException)。执行此操作的正确方法是使用 the 使用的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();
}

此外,如果您要分叉自己的线程,您还可以设置未捕获的异常处理程序:

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

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

于 2012-04-27T13:54:58.310 回答