有没有办法不使用'实例'与我无法扩展的对象?

时间:2015-07-15 12:58:03

标签: java oop exception exception-handling

我有一个自定义异常,几乎没有从Exception类继承的属性。

根据Exception的实例,我想返回一个代码。 代码:

public int manageException(Exception exception) {               
    int code = 0;               

    if (exception instanceof MyCustomException) {       
        code = ((MyCustomException) exception).getCode();       
    } else if (exception instanceof NestedRuntimeException) {       
        code = 444;         
    } else if (exception instanceof HibernateException) {       
        code = 555;         
    } else {        
        code = 666;
    }       

    return code;
}

2 个答案:

答案 0 :(得分:2)

你可以像这样使用重载:

public int manageException(MyCustomException e) {
    return e.getCode();
}

public int manageException(NestedRuntimeException e) {
    return 444;
}

public int manageException(HibernateExceptionexception e) {
    return 555;
}

public int manageException(Exception e) {
    return 666;
}

@ T.J发表评论后编辑。克劳德:

请记住,为了调用正确的方法,您仍然需要多个catch块。重载基于异常的编译时类型。只需执行catch (Exception e) { int code = this.manageException(ex); }即可返回666

答案 1 :(得分:1)

如果要将异常类型映射到不同的错误代码,可以使用地图:

Map<Class<? extends Exception>, Integer> map = new HashMap<> ();
map.put (Exception.class, 5);
map.put (NullPointerException.class, 42);

try {
  throw null; //throws NPE
} catch (Exception e) {
  System.out.println (map.get (e.getClass ())); //output is 42
}

我认为这很容易消耗,因为您可以从配置文件中读取映射而不是硬编码,因此您可以添加其他异常和错误代码而无需更改代码。

你必须测试map.get()的返回值为null,因为它可能是你之前没有指定的异常,因此没有映射到它的Integer。

注意:如第一条评论中所述,只有在您希望将类完全映射到错误代码时才会有效。如果异常的子类应该具有与其超类相同的错误代码,则此解决方案将无法在不进行修改的情况下工作。