异常

异常

异常指的就是程序在 运行时 出现错误时通知调用者的一种机制.
编译时错误:例如写代码出现拼写错误飘红, System.out.println 拼写错了, 写成了 system.out.println.
运行时异常:程序已经编译通过得到 class 文件了, 再由 JVM 执行过程中出现的错误.

防御式编程

LBYL: Look Before You Leap. 在操作之前就做充分的检查.
EAFP: It’s Easier to Ask Forgiveness than Permission. “事后获取原谅比事前获取许可更容易”. 也就是先操作, 遇到问题再处理.

捕获异常

try{
 	有可能出现异常的语句 ;
} [catch (异常类型 异常对象) {
	 出现异常后的处理行为;
} ]
[finally {
异常的出口(用于处理善后工作,会在最后执行);
}]
  • catch 和 finally 都可以根据情况选择加或者不加.

示例1

try{
	System.out.println(10/0);
} catch (ArithmeticException e){
	System.out.println("算术异常");
}
System.out.println("hello");

//结果为
算术异常
hello
  • 一旦 try 中出现异常, 那么 try 代码块中的程序就不会继续执行, 而是交给 catch 中的代码来执行. catch 执行完毕会继续往下执行

示例2——多个catch

int[] arr = {1, 2, 3};
try {
  System.out.println("before");
  arr = null;
  System.out.println(arr[100]);
  System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
  System.out.println("这是个数组下标越界异常");
  e.printStackTrace();
} catch (NullPointerException e) {
  System.out.println("这是个空指针异常");
  e.printStackTrace();
}
System.out.println("after try catch");

// 执行结果
before
这是个空指针异常
java.lang.NullPointerException
at demo02.Test.main(Test.java:12)
after try catch

示例3—— 多个异常的处理方式完全相同

  • 当出现第一个异常时,捕获第一个异常,之后的catch将不会被执行,那么要捕获多个异常如下代码
try {
     System.out.println(10 / 0);
} catch (ArithmeticException | NullPointerException e){
      e.printStackTrace();   //查看出现异常代码的调用栈.
      System.out.println("hello");
}
System.out.println("world");

//结果为
java.lang.ArithmeticException: / by zero
	at com.test.demo.ec.main(ec.java:13)				//打印栈上的追踪信息
hello
world

示例4——catch 只能处理对应种类的异常

int[] arr = {1, 2, 3};
try {
  System.out.println("before");
  arr = null;
  System.out.println(arr[100]);
  System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
  e.printStackTrace();
}
System.out.println("after try catch");

// 执行结果
before
Exception in thread "main" java.lang.NullPointerException
at demo02.Test.main(Test.java:11)
  • catch 语句不能捕获到刚才的空指针异常. 因为异常类型不匹配

示例5—— finally 表示最后的善后工作, 例如释放资源

int[] arr = {1, 2, 3};
try {
  System.out.println("before");
  arr = null;
  System.out.println(arr[100]);
  System.out.println("after");
} catch (Exception e) {
  e.printStackTrace();
} finally {
  System.out.println("finally code");
}
// 执行结果
before
java.lang.NullPointerException
at demo02.Test.main(Test.java:12)
finally code

无论是否存在异常, finally 中的代码一定都会执行到. 保证最终一定会执行到 Scanner 的 close 方法.

示例6——使用 try 负责回收资源

将 Scanner 对象在 try 的 ( ) 中创建, 就能保证在 try 执行完毕后自动调用 Scanner的 close 方法.

try (Scanner sc = new Scanner(System.in)) {
  int num = sc.nextInt();
  System.out.println("num = " + num);
} catch (Exception e) {
  e.printStackTrace();
}

示例7——当未定义捕获某个异常时, 就会沿着调用栈向上传递,如果一直都没有的话,就会交给JVM处理,程序异常终止。

“调用栈”
方法之间是存在相互调用关系的, 这种调用关系我们可以用 “调用栈” 来描述. 在 JVM 中有一块内存空间称为 “虚拟机栈” 专门存储方法之间的调用关系. 当代码中出现异常的时候, 我们就可以使用 e.printStackTrace(); 的方式查看出现异常代码的调用栈.

1、沿着调用栈向上传递
public static void main(String[] args) {
  try {
    func();
 } catch (ArrayIndexOutOfBoundsException e) {
    e.printStackTrace();
 }
  System.out.println("after try catch");
}
public static void func() {
  int[] arr = {1, 2, 3};
  System.out.println(arr[100]);
}

// 执行结果
java.lang.ArrayIndexOutOfBoundsException: 100
at demo02.Test.func(Test.java:18)
at demo02.Test.main(Test.java:9)
after try catch


2、交给JVM处理,程序异常终止
public static void main(String[] args) {
  func();
    System.out.println("after try catch");
}
public static void func() {
  int[] arr = {1, 2, 3};
  System.out.println(arr[100]);
}

// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at demo02.Test.func(Test.java:14)
at demo02.Test.main(Test.java:8)

异常处理流程

  • 程序先执行 try 中的代码
  • 如果 try 中的代码出现异常, 就会结束 try 中的代码, 看和 catch 中的异常类型是否匹配.
  • 如果找到匹配的异常类型, 就会执行 catch 中的代码
  • 如果没有找到匹配的异常类型, 就会将异常向上传递到上层调用者.
  • 无论是否找到匹配的异常类型, finally 中的代码都会被执行到(在该方法结束之前执行).
  • 如果上层调用者也没有处理的了异常, 就继续向上传递.一直到 main 方法也没有合适的代码处理异常, 就会交给 JVM 来进行处理, 此时程序就会异常终止

抛出异常

除了 Java 内置的类会抛出一些异常之外, 程序猿也可以手动抛出某个异常. 使用 throw 关键字完成这个操作.

public static void main(String[] args) {
System.out.println(divide(10, 0));
}
public static int divide(int x, int y) {
if (y == 0) {
throw new ArithmeticException("抛出除 0 异常");
}
return x / y;
}
// 执行结果
Exception in thread "main" java.lang.ArithmeticException: 抛出除 0 异常
at demo02.Test.divide(Test.java:14)
at demo02.Test.main(Test.java:9)

在这个代码中, 我们可以根据实际情况来抛出需要的异常. 在构造异常对象同时可以指定一些描述性信息.

异常说明

我们在处理异常的时候, 通常希望知道这段代码中究竟会出现哪些可能的异常.
我们可以使用 throws 关键字, 把可能抛出的异常显式的标注在方法定义的位置. 从而提醒调用者要注意捕获这些异常.

public static int divide(int x, int y) throws ArithmeticException {
	if (y == 0) {
		throw new ArithmeticException("抛出除 0 异常");
	}
	return x / y;
}

finally的注意事项

finally 中的代码保证一定会执行到. 这也会带来一些麻烦.

public static void main(String[] args) {
	System.out.println(func());
}
public static int func() {
	try {
		return 10;
	} finally {
		return 20;
	}
}

// 执行结果
20

finally 执行的时机是在方法返回之前(try 或者 catch 中如果有 return 会在这个 return 之前执行 finally). 但是如果finally 中也存在 return 语句, 那么就会执行 finally 中的 return, 从而不会执行到 try 中原有的 return.一般我们不建议在 finally 中写 return (被编译器当做一个警告).

Java异常体系

下图表示 Java 内置的异常类之间的继承关系:
在这里插入图片描述

  • 顶层类 Throwable 派生出两个重要的子类, Error 和 Exception
  • Error 指的是 Java 运行时内部错误和资源耗尽错误. 应用程序不抛出此类异常. 这种内部错误一旦出现,除了告知用户并使程序终止之外, 再无能无力. 这种情况很少出现.
  • Exception 是我们程序猿所使用的异常类的父类.
  • Exception 有一个子类称为 RuntimeException , 这里面又派生出很多我们常见的异常类
    NullPointerException , IndexOutOfBoundsException 等.

Java语言规范将派生于 Error 类或 RuntimeException 类的所有异常称为 非受查异常, 所有的其他异常称为 受查异常.

受查异常——若代码抛出受查异常, 那么必须显式进行处理.

Scanner 的构造方法, 存在 FileNotFoundException 这样的异常说明.

public Scanner(File source) throws FileNotFoundException {
	...
}

如 FileNotFoundException 这样的异常就是受查异常. 如果不显式处理, 编译无法通过.

示例:

public static void main(String[] args) {
System.out.println(readFile());
}
public static String readFile() {
// 尝试打开文件, 并读其中的一行.
File file = new File("d:/test.txt");
// 使用文件对象构造 Scanner 对象.
Scanner sc = new Scanner(file);
return sc.nextLine();
}
// 编译出错
Error:(13, 22) java: 未报告的异常错误java.io.FileNotFoundException; 必须对其进行捕获或声明以便抛出

处理方法1:使用 try catch 包裹起来

public static void main(String[] args) {
	System.out.println(readFile());
}
public static String readFile() {
	File file = new File("d:/test.txt");
	Scanner sc = null;
	try {
		sc = new Scanner(file);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
	return sc.nextLine();
}

处理方法2:在方法上加上异常说明, 相当于将处理动作交给上级调用者

public static void main(String[] args) {
	try {
		System.out.println(readFile());
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
}
public static String readFile() throws FileNotFoundException {
	File file = new File("d:/test.txt");
	Scanner sc = new Scanner(file);
	return sc.nextLine();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值