java异常总结

一.异常是什么?
程序在运行过程中发生由于外部问题(如硬件错误、输入错误)等导致的程序异常事件。
在Java等面向对象的编程语言中,异常本身是一个对象,产生异常就是产生了一个异常对象。
二.常见的异常
(1)除以 0

System.out.println(10 / 0);
// 执行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero

(2)数组下标越界

int[] arr = {1, 2, 3};
System.out.println(arr[100]);
// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100

(3)访问 null 对象

public class Test {
    public int num = 10;
    public static void main(String[] args) {
        Test t = null;
        System.out.println(t.num);
    }
}
// 执行结果
Exception in thread "main" java.lang.NullPointerException

所谓异常指的就是程序在 运行时 出现错误时通知调用者的一种机制.

三. 异常的基本用法
(1)捕获异常

try{    
    有可能出现异常的语句 ; 
}[catch (异常类型 异常对象) {
} ... ]
[finally {
    异常的出口
}]

[ ] 中的语句视情况添加。

try 代码块中放的是可能出现异常的代码.
catch 代码块中放的是出现异常后的处理行为.
finally 代码块中的代码用于处理善后工作, 会在最后执行.
其中 catch 和 finally 都可以根据情况选择加或者不加.

在运行过程过程中,遇到异常,如果你自已不处理的话,一般是JVM处理,会直接退出。
如何处理来看几个例子
1.

int[] arr = {1, 2, 3};
try {
    System.out.println("before");
    System.out.println(arr[100]);
    System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {   //catch括号中的异常对象应该与try语句中异常对象类型一样否则还是由JVM处理
    // 打印出现异常的调用栈
    e.printStackTrace(); // 当代码中出现异常的时候, 我们就可以使用  e.printStackTrace();  的
方式查看出现异常代码的调用栈.
}
System.out.println("after try catch");
// 执行结果
before
java.lang.ArrayIndexOutOfBoundsException: 100
    at demo02.Test.main(Test.java:10)
after try catch

我们发现, 一旦 try 中出现异常, 那么 try 代码块中的程序就不会继续执行, 而是交给 catch 中的代码来执行. catch 执行完毕会继续往下执行.
2.

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

一段代码可能会抛出多种不同的异常, 不同的异常有不同的处理方式. 因此可以搭配多个 catch 代码块.如果多个异常的处理方式是完全相同, 也可以写成这样

catch (ArrayIndexOutOfBoundsException | NullPointerException e) { 
  ... 
} 

也可以用一个 catch 捕获所有异常(不推荐)

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(); 
} 
System.out.println("after try catch"); 
 
// 执行结果 
before 
java.lang.NullPointerException 
  at demo02.Test.main(Test.java:12) 
after try catch 

由于 Exception 类是所有异常类的父类. 因此可以用这个类型表示捕捉所有异常.
4.

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 方法.
finally语句执行在方法结束最后一步。

(2)关于异常的处理方式
异常的种类有很多, 我们要根据不同的业务场景来决定.

对于比较严重的问题(例如和算钱相关的场景), 应该让程序直接崩溃, 防止造成更严重的后果
对于不太严重的问题(大多数场景), 可以记录错误日志, 并通过监控报警程序及时通知程序猿
对于可能会恢复的问题(和网络相关的场景), 可以尝试进行重试.

异常处理流程

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

(3)抛出异常
除了 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; 
} 

四.Java 异常体系
在这里插入图片描述

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

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

如果一段代码可能抛出 受查异常, 那么必须显式进行处理.

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; 必须对其进行捕获或声明以便抛出 

如 FileNotFoundException 这样的异常就是受查异常. 如果不显式处理, 编译无法通过.
显式处理的方式有两种:
a) 使用 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(); 
} 

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

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(); 
} 

别忘了 IDEA 神奇的 alt + enter, 能够快速修正代码.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值