抛出

Java 的数据类型与异常

Jim White

Java Developer

处理方式

  • 受检异常需要"处理"
    • 运行时异常可选处理
  • 两种"处理"方式
    • 用 try/catch 捕获 Exception 并编写处理代码
    • "抛出"异常
  • 优先用 try/catch 处理异常
    • 但并非总能做到,有时集中处理更好
Java 的数据类型与异常

throws 关键字

  • 在任意方法上用 throws 将异常传回给调用方
    • 而不是在本方法内处理
    • 称为"抛出异常"或"传递责任"
    • 即把处理异常的责任交给调用者
  • throws 后用逗号分隔列出异常类型
    • 表示调用方需预期的异常类型
public static void someMethod() throws IndexOutOfBoundsException, 
NegativeArraySizeException, NullPointerException {
  // method code
}
Java 的数据类型与异常
throws 示例

常规 try-catch 处理 Exception

public static void main(String[] args) {
  someMethod();
}
public static void someMethod(){
  try {
    ArrayList<String> games
      = new ArrayList<String>();
    games.add("Monopoly");
    games.add("Chess");
    games.get(3);
  } catch (IndexOutOfBoundsException e) {
    System.out.println(
   "Oops - trying to get non-existent item");
  }
}

用 throws 处理 Exception

public static void main(String[] args) {
  try {
    someMethod();
  } catch (IndexOutOfBoundsException e) {
    System.out.println(
   "someMethod tried to get non-existent item");
  }
}
public static void someMethod()
      throws IndexOutOfBoundsException {
  ArrayList<String> games
    = new ArrayList<String>();
  games.add("Monopoly");
  games.add("Chess");
  games.get(3);
}
Java 的数据类型与异常

何时使用 throws

  • "传递责任"或抛出异常通常应避免
    • 更好的做法通常是在异常发生处 try-catch
  • 需要抛出而非 try-catch 的原因包括:
    • 发生异常的方法不知道如何恢复
    • 集中处理以减少重复的 try/catch 代码

抛出异常通常用于自定义异常

1 Photo from https://unsplash.com/@philipparosetite
Java 的数据类型与异常

捕获并重新抛出

  • 可以"重新抛出"Exception
    • 调用方法也用 throws,而不是 try/catch
  • main 重新抛出会导致应用停止

异常可重新抛给调用方法

Java 的数据类型与异常

重新抛出示例

public class RethrowExample {
    public static void main(String[] args) {
        try {
            method1(0);
        } catch (ArithmeticException e) {
            System.out.println("Oops - tried a bad quotient");
        }
    }
    public static void method1(int divisor) throws ArithmeticException {
        method2(divisor);
    }
    public static void method2 (int divisor) throws ArithmeticException {
        int z = 5/divisor;
        System.out.println(z);
    }
}
Java 的数据类型与异常

Passons à la pratique !

Java 的数据类型与异常

Preparing Video For Download...