如何获取Eclipse中的方法抛出的具体异常列表 [英] How to get a list of concrete Exceptions thrown by a method in Eclipse

查看:453
本文介绍了如何获取Eclipse中的方法抛出的具体异常列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以获取一个可以抛出方法的具体异常的列表(和catch)?

Is is possible to get a list (and catch) of the concrete exceptions that can be thrown by a method?

我正在调用使用异常层次结构的API,但只能声明方法的顶级异常。我想要能够提供基于异常的特定行为,但是我不想跟踪代码以找到可以抛出的具体异常。

I am calling an API that uses a hierarchy of exceptions, but only declares the top level exception to a method. I want to be able to provide specific behaviour based on the exception, but I don't want to have to trace through the code to find the concrete exceptions that can be thrown.

可能会增加复杂性,API包含多个由接口分隔的图层。

There may be added complications that the API contains a number of layers separated by interfaces.

简单示例:

public interface MyInterface {
  void doShakyStuff() throws Exception;
}

public class MyImpl implements MyInterface {
  public void doShakyStuff() throws Exception{
    double rand = Math.random();
    if( rand > 0.1 ){
      throw new IOException();
    }
    if( rand > 0.5 ){
      throw new IllegalAccessException();
    }
    else{
      throw new InterruptedException();
    }
  }
}

我想能够创建以下try / catch尽可能完整,然后调整:

I want to be able to create the following try/catch as completely as possible and then tweak afterwards:

public class MyClass{
  private MyInterface interface;

  public void doStuff(){
    try{
      interface.doShakyStuff();
    }catch(IOException e){
      // ...
    } catch( IllegalAccessException e){
      // ...
    } catch( InterruptedException e){
      // ...
    } catch(Exception e){
      // something else
    }
  }
}


推荐答案

答案是:否。

该方法声明它抛出的内容。如果只是声明一个顶级异常(例如你的例子中的 Exception ),那么这就是你所有的IDE都会知道/告诉你的。

The method declares what it throws. If it's only declaring a top-level exception (i.e. Exception in your example) ... then that's all your IDE is going to know about / tell you to catch.

要查找可能抛出的每个子类,您必须查看javadocs和/或代码来查找您感兴趣的子类或特定的子类。

To find every subclass it could throw you'd have to look at the javadocs and/or code to find the subclasses or specific subclass being thrown that you're interested in.

最终,如果您使用的是一个引发异常超类的API,并且有一些理由需要了解具体的子类...这是一个非常好的设计API。在编写API时抛出超类的一点是,无论执行什么子类,都只有一行逻辑来处理它。

Ultimately if you're using an API that's throwing a superclass of an exception, and there's some reason you need to know the concrete subclass ... it's a badly designed API. The point of throwing the superclass when writing an API is that there's only a single line of logic to deal with it regardless of which subclass is really being thrown.

这篇关于如何获取Eclipse中的方法抛出的具体异常列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆