demonrethrow.java

来自「压缩包内是近180多个针对Java初学者编写的简单实例」· Java 代码 · 共 39 行

JAVA
39
字号
//重新抛出异常示例。
class Rethrow {
  public static void generateException() {
    // longArray数组的长度大于shortArray
    int longArray[] = {2, 4, 8,16, 32, 64,128};
    int shortArray[] = { 1, 0, 2, 2, 0 ,2};

    for(int i=0; i< longArray.length; i++) {
      try {
        System.out.println(longArray [i] + " / " +
                           shortArray [i] + " is " +
                           longArray [i]/ shortArray [i]);
      }
      catch (ArithmeticException  e) {
        // 捕捉异常
        System.out.println("Can't divide by Zero!");
      }
      catch (ArrayIndexOutOfBoundsException e) {
        // 捕捉异常
        System.out.println("No matching element found.");
        throw e; // 重新抛出异常
      }
    }
  }  
}

class DemonRethrow {
  public static void main(String args[]) {
    try {
      Rethrow.generateException();
    }
    catch(ArrayIndexOutOfBoundsException e) {
      //捕获重新抛出的异常
     System.out.println("error!! -- " +
                        "program terminated.");
    }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?