[英]Caught and declared exception in Java?
In Java, if I declare and caught an exception, can I handle the exception in a caller anyway?在 Java 中,如果我声明并捕获了异常,我是否仍然可以在调用者中处理异常? Or it needs not to be caught to handle it by caller?或者它不需要被调用者捕获来处理它?
class A {
void first() throws Exception {
try {
throw new Exception("my exception")
} catch (Exception e) {
log.message("Error in first()", e.getCouse)
throw e
}
}
}
class B {
Result second(A a) {
try {
a.first()
} catch (Exception e) {
log.message("Caught in B class", e.message)
return new Result(result: null, error: e.message)
}
}
second(A a)
}
You can simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.).您可以简单地重新抛出您捕获的异常(显然周围的方法必须通过其签名等允许这样做)。 The exception will maintain the original stack trace.异常将保持原始堆栈跟踪。
catch (WhateverException e) {
throw e;
}
You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:您还可以将异常包装在另一个异常中,并通过将 Exception 作为 Throwable 作为 cause 参数传递来保留原始堆栈跟踪:
try
{
...
}
catch (Exception e)
{
throw new YourOwnException(e);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.