希望得到解释,通过在我的方法 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
calls checkArray
,但方法可以有几十种。
当代码中发生异常时,它会中断当前方法并将控制权交还给堆栈跟踪上的前一个方法。如果此方法可以处理异常(带有catch
), the catch
将被执行,异常将停止冒泡。如果没有,异常将在堆栈跟踪中冒泡。最终,如果它到达main
和main
无法处理它,程序将因错误而停止。
在您的具体情况下,throw new ABException()
创建并抛出一个ABException
这会打断checkArray
方法。然后在你的 main 中捕获异常catch(ABException ab)
。因此,根据您的问题,您可以说这段代码将异常“向上调用链”传递。
还有很多事情要说,特别是与检查/非检查异常相关的事情。如果您有一些更具体的问题,请随时提问。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)