希望通过在我的方法 throws 子句中声明异常来解释将异常向上传递到调用链意味着什么,以及我为什么要这样做。
这是我对自己抛出异常的理解的一个例子。
public class ExceptionThrow {
char[] charArray = new char[] { 'c', 'e', 'a', 'd' };
void checkArray() throws ABException {
for (int i = 0; i < charArray.length; i++) {
switch (charArray[i]) {
case 'a':
throw new ABException();
case 'b':
throw new ABException();// creating the instance of the
// exception anticipated
default:
System.out.println(charArray[i] + " is not A or a B");
}
}
}
public static void main(String[] args) {
ExceptionThrow et = new ExceptionThrow();
try {
et.checkArray();
} catch (ABException ab) {
System.out.println(ab.getMessage() + " An exception did actually occur");
} finally {
System.out.println("This block will always execute");
}
}
}
class ABException extends Exception {
}
我如何将异常“向上传递到调用链”?
问候 阿里安
最佳答案
“调用链”,通常也称为“堆栈跟踪”,是导致单行执行的所有嵌套方法调用的列表。在您的例子中,它的深度是 2:main
调用 checkArray
,但是可以有几十种方法。
当代码中发生异常时,它会中断当前方法并将控制权交还给堆栈跟踪中的前一个方法。如果此方法可以处理异常(使用catch
),则执行catch
,异常将停止冒泡。如果不是,异常将在堆栈跟踪中冒泡。最终,如果它到达 main
而 main
无法处理它,程序将因错误而停止。
在您的特定情况下,throw new ABException()
创建并抛出一个 ABException
中断 checkArray
方法。然后使用 catch(ABException ab)
在您的 main 中捕获异常。因此,根据您的问题,您可以说此代码将异常“向上传递到调用链”。
还有很多话要说,特别是与已检查/未检查的异常有关。如果您有一些更具体的问题,请随时提出。
关于java - 向上传递调用链异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8428291/