执行过程中所发生的异常事件可分为两大类
try-catch异常处理注意
try-catch-finally练习
练习1
public class Exception01 { public static int method() { try { String[] names = new String[3]; if (names[1].equals("tom")) { System.out.println(names[1]); } else { names[3] = "hspedu"; } return 1; } catch (ArrayIndexOutOfBoundsException e) { return 2; } catch (NullPointerException e) { return 3; } finally { return 4; } } public static void main(String[] args) { System.out.println(method());//4 } }
练习2
public class TryCatchExercise { public static void main(String[] args) { System.out.println(method()); } public static int method() { int i = 1; try { i++; // i = 2 String[] names = new String[3]; if (names[1].equals("tom")) { // 空指针异常 System.out.println(names[1]); } else { names[3] = "hspedu"; } return 1; } catch (ArrayIndexOutOfBoundsException e) { return 2; } catch (NullPointerException e) { return ++i; } finally { return ++i; } } public static void main(String[] args) { System.out.println(method());//4 } }
练习3
注意返回值,如果有finally,返回值会以临时变量的形式存储,catch异常后的return的结果会保存在一个临时变量中,此时会继续执行finally,之后再返回这个临时变量3 => i = 4;3
public class TryCatchExercise { public static void main(String[] args) { System.out.println(method()); } public static int method() { int i = 1; try { i++; // i = 2 String[] names = new String[3]; if (names[1].equals("tom")) { // 空指针异常 System.out.println(names[1]); } else { names[3] = "hspedu"; } return 1; } catch (ArrayIndexOutOfBoundsException e) { return 2; } catch (NullPointerException e) { return ++i; // i = 3 => 保存临时变量 temp = 3; } finally { ++i; System.out.println("i = " + i); // i = 4 } } }
public class CustomException { public static void main(String[] args) { int age = 180; if (!(age >= 18 && age <= 120)) { throw new AgeException("年龄需要在18~120之间"); } System.out.println("年龄正常"); } } class AgeException extends RuntimeException { public AgeException(String message) { super(message); } }