从变量中抛出异常

问题描述 投票:1回答:2

使用java,我想做类似的事情

try {
  someMethod();
} catch (Throwable x) {
  x.setMessage("Some comment " + x.getMessage());
  throw x;
}

也就是说,我不知道“someMethod”会抛出什么。无论是什么,我想在其消息的开头添加一条消息,然后抛出错误。但是Throwable没有setMessage()方法。

我可以做一个Class<? extends Throwable> cls = x.getClass();来获取类类型,但我不确定语法。我不能做一个throw new cls("Comment " + x.getMessage());我肯定必须有一个相当简单的方法来做这个,当你不知道抛出的throwable的类。

java exception
2个回答
0
投票

你可以简单地抓住Exception抛出的someMethod(),然后用你想要的信息重新抛出它。

就像是,

try {
   someMethod();
} catch(Exception ex) {
   /* Optional: Log Error */
   Logger.error(..., ex);
   throw new Exception("Error Occurred While Processing Request.", ex);
}

如果需要,您还可以创建并抛出一个已检查的异常,如下所示,

自定义异常类:

public class CustomException extends Exception {
    /* Optional: Add Serial UID */

    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }

    public CustomException(Throwable cause) {
        super(cause);
    }
}

码:

try {
   someMethod();
} catch(Exception ex) {
   /* Optional: Log Error */
   Logger.error(..., ex);
   throw new CustomException("Error Occurred While Processing Request.", ex);
}

2
投票

而不是捕捉Throwable(这几乎总是一个错误),你可以创建一个自定义的RuntimeException并包装你捕获的异常。

public class MyException extends RuntimeException {
    public MyException(String message, Throwable cause) {
        super(message, cause);
    }
}

try {
    someMethod();
} catch(Exception e) {
    throw new MyException("A major error has occurred!", e);
}
© www.soinside.com 2019 - 2024. All rights reserved.