博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
认识异常
阅读量:3959 次
发布时间:2019-05-24

本文共 7306 字,大约阅读时间需要 24 分钟。

1.异常的背景

1)初识异常

除以0:

System.out.println(10/0);
Exception in thread "main" java.lang.ArithmeticException: / by zero	at Main.main(Main.java:3)

数组下标越界

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

访问null对象

private int num=100;    public static void main(String[] args) {
Main t=null; System.out.println(t.num); }
Exception in thread "main" java.lang.NullPointerException

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

2)防御式编程
LBYL:在操作之前就做充分地检查
EAFP:事后获取原谅比事前获取许可更容易,也就是“先操作,遇到问题再处理”。

2.异常的基本用法

1)捕获异常

基本语法:try{
有可能出现异常的语句;
}[catch(异常类型 异常对象){
}…]
[finally{
异常的出口
}]
说明:try代码块中放的是可能出现异常的代码
catch代码块中放的是出现异常后的处理行为
finally代码块中的代码用于处理善后工作
其中catch和finally都可以根据情况选择加或者不加
代码示例1 不处理异常

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

一旦出现异常,程序就终止了,after就没有正确输出

代码示例2:使用try catch后的程序执行过程

int[] arr = {
1, 2, 3}; try {
System.out.println("before"); System.out.println(arr[100]); System.out.println("after"); }catch(ArrayIndexOutOfBoundsException e){
//打印出现异常的调用栈 e.printStackTrace(); } System.out.println("after try catch"); //执行结果 before after try catch java.lang.ArrayIndexOutOfBoundsException: 100

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

代码示例3: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

此时,catch语句不能捕获到刚才的空指针异常,因为异常类型不匹配

代码示例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){
//打印出现异常的调用栈 System.out.println("这个是数组下标越界异常"); e.printStackTrace(); }catch(NullPointerException e){
System.out.println("这个是空指针异常"); e.printStackTrace(); } System.out.println("after try catch"); //执行结果 before java.lang.NullPointerException 这个是空指针异常 at Main.main(Main.java:11) after try catch

如果多个异常的处理方式是完全相同的,也可以写成这样

catch(ArrayIndexOutOfBoundsException|NullPointerException e){ }
代码示例5:也可以用一个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");//执行结果beforejava.lang.NullPointerExceptionafter try catch

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

代码示例6: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 finally code

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

代码示例7:使用try负责回收资源

try (Scanner sc=new Scanner(System.in)){
int num=sc.nextInt(); System.out.println("num="+num); }catch(Exception e) {
//打印出现异常的调用栈 e.printStackTrace(); }

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

代码示例8:如果本方法没有合适的处理异常的方式,就会沿着调用栈向上传递

public static void main(String[] args) {
try{
func(); }catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace(); } System.out.println("after try cach"); } public static void func(){
int[] arr={
1,2,3}; System.out.println(arr[100]); } //执行结果 after try cach java.lang.ArrayIndexOutOfBoundsException: 100 at Main.func(Main.java:12) at Main.main(Main.java:4)

代码示例9:如果一直向上传递都没有合适的方法处理异常,最终就会交给JVM处理,程序就会异常终止

public static void main(String[] args) {
func(); System.out.println("after try cach"); } public static void func(){
int[] arr={
1,2,3}; System.out.println(arr[100]); } //执行结果 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100 at Main.func(Main.java:8) at Main.main(Main.java:3)

可见:程序已经异常终止了,没有执行到System.out.println(“after try cach”);这一行

2)异常的处理流程
a) 程序先执行try中的代码
b) 如果try中的代码出现异常,就会结束try中的代码,看和catch中的异常类型是否匹配
c) 如果找到匹配的异常类型,就会执行catch中的代码
d) 如果没有找到匹配的异常类型,就会将异常向上传递到上层调用者
e) 无论是否找到匹配的异常类型,finally中的代码都会被执行到
f) 如果上层调用者也没有处理了的异常,就继续向上传递
g) 一直到main方法也没有合适的代码处理异常,就会交给1JVM来进行处理,此时程序就 会异常终止
3)抛出异常:使用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 Main.divide(Main.java:8) at Main.main(Main.java:4)

4)异常说明:使用throw关键字

5)关于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.

3.java异常体系

顶层类throwable派生出两个重要得子类,error和exception

其中error指的是java运行时内部错误和资源耗尽错误,应用程序不抛出此类异常。这种内部错误一旦出现,除了告知用户并使程序终止外,在无能为力
Exception是我们·所用的异常类的父类
其中Exception有一个子类称为RuntimeExeption,这里面又派生出很多我们常见的异常类
NullPointerException,IndexOutOfBoundsException等

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

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

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(){
File file=new File("d:/test.txt"); Scanner sc=null; return sc.nextLine(); }

4.自定义异常类

注意事项:
自定义异常类通常会继承自Exception或者RuntimeException
继承自Exception异常默认是受查异常
继承自RuntimeException得异常默认是非受查异常

转载地址:http://yylzi.baihongyu.com/

你可能感兴趣的文章