我在Java中有一个基本问题:
我有两种方法:functionA
和functionB
。 functionA
调用functionB
,并且functionB
引发异常。对functionB
的调用在functionA
的try范围内。
现在,我还希望functionA
进入其catch范围。
有什么办法吗?
最佳答案
如果在methodB
中引发了异常并且您将其捕获,则将其传播到methodA
的一种方法是将其重新抛出:
void methodB() throws SomeException {
try {
//Something that can throw SomeException
} catch (SomeException e) {
//rethrow e
throw e;
}
}
void methodA() {
try {
methodB();
} catch (SomeException e) {
//this block will run if methodB throws SomeException
}
}
但是如果需要的话,您可能根本不应该在
methodB
中捕获该异常,而应将其自动传播到methodA
:void methodB() throws SomeException {
//Something that can throw SomeException: don't catch it
}
void methodA() {
try {
methodB();
} catch (SomeException e) {
//this block will run if methodB throws SomeException
}
}