是否可以捕获正在运行的 try-catch block 的当前类中的方法?例如:
public static void arrayOutOfBoundsException(){
System.out.println("Array out of bounds");
}
.....
public static void doingSomething(){
try
{
if(something[i] >= something_else);
}
catch (arrayOutOfBoundsException e)
{
System.out.println("Method Halted!, continuing doing the next thing");
}
}
如果这是可能,那么调用 catch 方法的正确方法是什么?
如果这是不可能,任何人都可以为我指出正确的方向,即如何阻止异常停止我在Java中的程序执行而无需创建任何异常包中的新类,或修复产生 ArrayOutOfBoundsException 错误的代码。
提前致谢,
Java菜鸟
最佳答案
您想要做的是处理 Exception .
public static void doingSomething(){
try {
if (something[i] >= something_else) { ... }
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Method Halted!, continuing doing the next thing");
}
}
这就是您所需要的。没有额外的类,没有额外的方法。
异常是一种可以“抛出”的特殊类型的类(您可以使用 throw
关键字自行抛出异常,或者 Java 可能会为您抛出一个异常,例如,如果您尝试访问不存在的数组索引或尝试对 null
执行某些操作)。抛出的异常将“解开”您的调用堆栈(从每个函数调用中“转义”),直到您的程序最终终止。除非你捕获
它,这正是上面语法的作用。
因此,如果您正在编写一个函数a()
,该函数调用了一个函数b()
,该函数又调用了一个函数c()
并且c()
抛出异常,但该异常没有在 b()
或 c()
中捕获,您仍然可以在 中捕获它>a()
:
void a() {
try {
b();
catch (SomeExceptionClass e) {
// Handle
}
}
也就是说,如果能够从一开始就防止异常抛出,那通常是一个更好的主意。在您的特定情况下,这是可能的,因为 Java 中的所有数组都知道它们自己的长度:
public static void doingSomething(){
if (i >= something.length) {
System.out.println("Method Halted!, continuing doing the next thing");
} else {
if (something[i] >= something_else) { ... }
}
}
关于java - 同一个 Java 类中的 Try-Catch-Throw,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2394773/