try 和 catch

Java 的数据类型与异常

Jim White

Java Developer

Java 中的问题

  • 应用可能出现问题
    • 错误输入
    • 代码错误
    • 意外情况
  • 这些问题称为"异常"
    • 会中断正常控制流
  • Java 会"抛出"异常
Java 的数据类型与异常

异常示例

public static void main(String[] args) {
    ArrayList<String> allStars = new ArrayList<String>();
    allStars.add("Mays");
    allStars.add("Aaron");
    allStars.add("Ruth");
    String last = allStars.get(3); // This will cause an exception
    System.out.println(last);
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of 
bounds for length 3
Java 的数据类型与异常

try

  • 用 try 块包裹可能抛出异常的代码
    • "先尝试该代码,如有问题交给 catch 处理"
try {
    // Statements to be executed and watched for exceptions
}
Java 的数据类型与异常

catch

  • 在 try 之后添加 catch 块
    • 作为处理程序,解决异常
    • 捕获的异常以参数传入该块
  • 某些异常必须使用 try/catch,其他可选
try {
    // Statements to be executed and watched for exceptions
} catch (<Exception type> <variable name>) {
    // Statements to execute if an exception has occurred
}
Java 的数据类型与异常

捕获 IndexOutOfBoundsException

try {
  ArrayList<String> allStars = new ArrayList<String>();
  allStars.add("Mays");
  allStars.add("Aaron");
  allStars.add("Ruth");
  String last = allStars.get(3); // Accessing an element that isn't there
  System.out.println(last);
} catch (IndexOutOfBoundsException e) {
  System.out.println("Oops - wrong index");
}
Oops - wrong index
Java 的数据类型与异常

多个 catch

  • 使用多个 catch 处理不同异常类型
  • 每个 catch 拥有自己的异常类型和变量
  • 发生异常时,Java 按顺序检查各 catch,直到匹配为止
try {
    ArrayList<String> nums 
      = new ArrayList<String>();
    nums.add("one");
    String last = nums.get(0);
    Integer.valueOf(last);
    System.out.println(last);
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println(
      "Oops - String not a number");
}
Oops - String not a number
Java 的数据类型与异常

捕获"所有"

  • 使用 catch (Exception variable){ } 作为兜底
    • 处理未被前面 catch 拦截的任何异常
try {
    // Code to try
} catch (IndexOutOfBoundsException eIndex) {
    System.out.println("Oops - wrong index");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops - String not a number");
} catch (Exception e) { // Handles all exceptions except the two above
    System.out.println("Something unplanned happened");
}
Java 的数据类型与异常

finally

  • finally 中的代码始终执行
// When exception happens
try {
    Integer.valueOf("one");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Oops
Doing cleanup

 

// When no exception gets thrown
try {
    Integer.valueOf("1");
} catch (NumberFormatException eValueOf) {
    System.out.println("Oops");
} finally {
    System.out.println("Doing cleanup");
}
Doing cleanup
Java 的数据类型与异常

Exception 对象

  • 传入 catch 的 Exception 对象包含丰富信息
  • 调用其方法了解问题原因
    • .getMessage():获取可读原因
    • .getClass():获取异常类/类型名
    • .printStackTrace():打印堆栈跟踪(见下页)
public class ExceptionExample {

    public static void main(String[] args) {
        try {
            Integer.valueOf("one");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
Java 的数据类型与异常

异常堆栈跟踪

  • 堆栈跟踪记录到问题位置的执行路径
    • 下方:上例代码的输出——包含打印的堆栈跟踪
For input string: "one"
java.lang.NumberFormatException: For input string: "one"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:661)
    at java.base/java.lang.Integer.valueOf(Integer.java:988)
    at foo/exceptions.ExceptionExample.main(ExceptionExample.java:7)
Java 的数据类型与异常

Passons à la pratique !

Java 的数据类型与异常

Preparing Video For Download...