Try-Catch-Throw在同一个Java类中

Car*_*los 0 java arrays error-handling exception-handling try-catch

是否有可能在当前类中捕获try-catch块正在运行的方法?例如:

  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");
    }
  }
Run Code Online (Sandbox Code Playgroud)

如果可能的话,调用catch方法的正确方法是什么?

如果这是不可能的,那么任何人都可以指出我正确的方向,如何阻止异常停止在Java中执行程序,不必在包中创建任何新类,或修复产生ArrayOutOfBoundsException错误的代码.

提前致谢,

一个Java新秀

Ada*_*kin 6

你想要做的是处理异常.

public static void doingSomething(){
    try {
        if (something[i] >= something_else) { ... }
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Method Halted!, continuing doing the next thing");
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是你所需要的.没有额外的课程,没有额外的方法.

Exception是一种特殊类型的类,可以"抛出"(你可以通过使用throw关键字自己抛出它,或者Java可能会为你抛出一个,例如,如果你试图访问不存在的数组索引或尝试对a null)执行某些操作.抛出的异常将"解包"您的调用堆栈(从每个函数调用中"转义"),直到程序最终终止.除非你catch,这正是上面的语法所做的.

因此,如果您正在编写一个函数a(),该函数b()调用一个调用函数c()c()抛出异常的函数,但该异常未被捕获b()或者c(),您仍然可以捕获它a():

void a() {
    try {
        b();
    catch (SomeExceptionClass e) {
        // Handle
    }
}
Run Code Online (Sandbox Code Playgroud)

也就是说,如果可以防止异常被抛出,那通常是一个更好的主意.在您的特定情况下,这是可能的,因为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) { ... }
    }
}
Run Code Online (Sandbox Code Playgroud)