Java异常处理

1 - 引子

/*
在使用计算机语言进行项目开发的过程中,即使程序员把代码写得尽善尽美,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如:客户输入数据的格式,读取文件是否存在,网络是否始终保持通畅等等
*/

2 - 什么是异常?

/*
1. 异常:在Java语言中,将程序执行中发生的不正常情况称为“异常”。 (开发过程中的语法错误和逻辑错误不是异常)

2. Java程序在执行过程中所发生的异常事件可分为两类:

Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源 耗尽等严重情况。比如:StackOverflowError和OOM。一般不编写针对性 的代码进行处理。

Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使 用针对性的代码进行处理,例如:

  1空指针访问

  2试图读取不存在的文件

  3网络连接中断

  4数组角标越界

3. 对于这些错误,一般有两种解决方法:一是遇到错误就终止程序 的运行。另一种方法是由程序员在编写程序时,就考虑到错误的 检测、错误消息的提示,以及错误的处理

4. 捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。 比如:除数为0,数组下标越界等

分类:编译时异常和运行时异常

*/

package com.lzh.error;
/*
 * Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源 耗尽等严重情况。比如:StackOverflowError和OOM。一般不编写针对性 的代码进行处理
 */
public class ErrorTest {
    public static void main(String[] args) {
        // 1.java.lang.StackOverflowError 栈溢出
        // main(args);
        
        
        // 2.java.lang.OutOfMemoryError 堆溢出
        Integer[] array = new Integer[1024*1024*1024];
    }
}
ErrorTest.java

编译时异常和运行时异常

3 - 异常体系结构

/*
 异常体系结构

 java.lang.Throwable

  ①java.lang.Error:一般不编写针对性的代码进行处理

  ②java.lang.Exception:可以进行异常的处理


1.编译时异常(checked)

IOException  FileNotFoundException  ClassNotFoundException

2.运行时异常(unchecked)

  NullPointerException

  ArrayIndexOutOfBoundsException

  ClassCastException

  NumberFormatException

  InputMismatchException
*/

package com.lzh.error;

import java.util.Date;
import java.util.Scanner;
import org.junit.jupiter.api.Test;

public class ExceptionTest {
    // NullPointerException 空指针异常
    @Test
    public void test1() {
        Integer[] array = null; // 空指针举例
        System.out.println(array[0]);
    }
    // ArrayIndexOutOfBoundsException 角标越界
    @Test
    public void test2(){
        int[] array = new int[2]; // 数组角标越界举例
        System.out.println(array[2]);
    }
    // ClassCastException 类型转换异常
    @Test
    public void test3() {
        Object obj = new Date();
        String str = (String)obj;
        System.out.println(str);
    }
    // NumberFormatException 数字转换异常
    @Test
    public void test4() {
        String num = "123a";
        int number = Integer.parseInt(num);
        System.out.println(number);
    }
    // InputMismatchException 输入不匹配
    @Test
    public void test5() {
        Scanner scanner = new Scanner(System.in);
        int score = scanner.nextInt(); // 键盘输入abc
        System.out.println(score);
    }
    
}
运行时异常举例

异常体系结构图解

4 - 异常处理机制1 try-catch-finally

/*
异常处理:抓抛模型

过程1:"抛" -> 程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象,并将此对象抛出,一旦抛出对象以后,其后的代码不在执行。

过程2:"抓" -> ① try-catch-finally ② throws

try-catch-finally的使用

  try{

  // 可能出现异常的代码

  }catch(异常类型1 变量1){

  // 处理异常的方式1

  }catch(异常类型2 变量2){

  // 处理异常的方式2

  }

  ...

  finally{

  // 一定会执行的代码

  }

说明:

1 - finally是可选的,且可以相互嵌套

2 - 使用try将可能出现异常代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,去catch中进行匹配。

3 - 一旦try中的异常对象匹配到某个catch时,就进入catch中进行异常的处理。一旦处理完成,就跳出当前的try-catch结构(没有finally的情况),继续执行其后的代码。

4 - catch中的异常类型如果没有子父类关系,则谁声明在上,谁声明在下无所谓。catch中的异常类型如果满足子父类关系,则要求子类一定声明在父类上面。否则报错

5 - 常用的异常对象处理方式:①String getMessage() ②printStackTrace()

6 - try结构中声明的变量,出了结构就不能再被调用
*/

public class ExceptionTest1 {
    // try-catch-finally的使用
    @Test
    public void test1() {
        String str = "123a";
        try {
            int number = Integer.parseInt(str);
            System.out.println("hello");
        }catch(NumberFormatException e) {
//            System.out.println(e.getMessage());
//            System.out.println("数值转换异常");
            e.printStackTrace();
        }catch(NullPointerException e) {
            System.out.println(e);
            System.out.println("空指针异常");
        }catch(Exception e) {
            
        }
        System.out.println("321");
    }
}
代码示例

5 - try-catch-finally中finally的使用

/*
try-catch-finally中finally的使用:

1.finally是可选的

2.finally中声明的是一定会被执行的代码。即使catch中又出现了异常,try中又return语句,catch中有return语句等情况。

3.像数据库连接、输入输出流、网络编程Socket等资源。jvm是不能自动回收的,就需要我们手动的进行资源的释放。此时的资源释放,就需要声明在finally中。

体会1:使用try-catch-finally处理编译时异常,使得程序在编译时就不报错,但是运行时仍可能报错,相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现

体会2:开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally了。正对于编译时异常,我们说一定要考虑异常的处理。
*/

package com.lzh.error;

import java.util.Scanner;

import org.junit.Test;

public class FinallyTest {
    @Test
    public void test2() {
        Scanner scanner = new Scanner(System.in);
        int score = 0;
        try {
            System.out.print("请输入成绩:");
            score = scanner.nextInt();
        }catch(Exception e) {
            System.out.println(e);
        }finally {
            scanner.close(); // 回收资源
            System.out.println("成绩是"+score);
        }
    }
    @Test
    public void test1() {
        try {
            int a = 0;
            int b = 1;
            System.out.println(b/a);
        }catch(Exception e) {
            System.out.println(e);
            int[] array = new int[2];
            System.out.println(array[2]);
        }finally{
            System.out.println("一定会执行这里");
        }
    }
}
FinallyTest.java

6 - 异常处理机制2  throws

/*
 声明抛出异常是Java中处理异常的第二种方式

1 - 如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这 种异常,则此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理, 而由该方法的调用者负责处理

2 - 在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异常类型可 以是方法中产生的异常类型,也可以是它的父类

3 - 声明抛出异常:throw + 异常类型

"throw + 异常类型"写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象。此对象满足throw后异常类型时,就会被抛出,异常代码后续的代码,就不再执行

4 - 体会:try-catch-finally -> 真正的将异常给处理掉。而throws的方式只是将异常抛给了方法的调用这。并没有真正处理掉异常

5 - 开发中如何选择使用try-catch-finally 还是使用throws?

  ①如果父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throw是,意味着如果子类重写的方法中有异常,必须使用try-catch-finally方法处理

  ②执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws的方式进行处理,而执行的方法a可以考虑使用try-catch-finally方式进行处理。

*/

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class ThrowTest {
    
    public static void main(String[] args) {
        try {
            method2();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void method2() throws IOException{
        method1();
    }
    
    public static void method1() throws FileNotFoundException,IOException{
        File file = new File("hello.txt");
        FileInputStream fis = new FileInputStream(file);
        
        int data = fis.read();
        while(data != -1) {
            System.out.println((char)data);
            data = fis.read();
        }
        fis.close();
    }
}
ThrowTest.java

图解

7 -  重写方法声明抛出异常的原则 

8 - 手动抛出异常 throw

/*
关于异常对象的产生:

  ①系统自动生成的异常对象

  ②手动的生成一个异常对象,并抛出(throw)

 throw 的使用,见代码
*/

package com.lzh.error;

/*
 * 关于异常对象的产生:
 *     ①系统自动生成的异常对象
 *     ②手动的生成一个异常对象,并抛出(throw)
 */
public class StudentTest {
    public static void main(String[] args) {
        try {
            Student s = new Student();
            s.regist(-1001);
            System.out.println(s);
        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}

class Student{
    int id;
    public void regist(int id) throws Exception{
        if(id > 0) {
            this.id = id;
        }else {
            // System.out.println("输入格式错误!");
            // 手动抛出异常对象
            // throw new RuntimeException("您输入的数据非法!");
            throw new Exception("您输入的数据非法!");
        }
    }
}
手动抛出异常

9 - 开发者自定义异常类

/*
1 一般地,用户自定义异常类都是RuntimeException的子类。

2 自定义异常类通常需要编写几个重载的构造器。

3 自定义异常需要提供serialVersionUID

4 自定义的异常通过throw抛出。

5 自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类
*/

package com.lzh.error;
/*
 * 如何自定义异常类
 * 1.继承现有的异常结构:RuntimeException Exception
 * 2.提供全局常量:serialVersionUID
 * 3.提供构造器
 */
// 自定义异常类
public class MyException extends RuntimeException{
    
    static final long serialVersionUID = -3387516993124229948L;
    
    public MyException() {
        
    }
    public MyException(String message) {
        super(message);
    }
    
    // 测是自定义类
    public static void main(String[] args) {
        Students s1 = new Students();
        s1.register(1001);
        System.out.println(s1.id);
        
        try {
            Students s2 = new Students();
            s2.register(-1002);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

class Students{
    int id;
    public Students() {
        
    }
    
    public void register(int id) {
        if(id > 0) {
            this.id = id;
        }else {
            throw new MyException("不能输入负数!");
            // 错误示例:只有异常类才可以throw
            // throw new String("1111");
        }
    }
}
自定义异常类

10 - 异常处理练习

package com.lzh.exception_exer;

/*
编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算 两数相除。
对 数 据 类 型 不 一 致 (NumberFormatException) 、 缺 少 命 令 行 参 数 (ArrayIndexOutOfBoundsException、
除0(ArithmeticException)及输入负数(EcDef 自定义的异常)进行异常处理。

提示:
(1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
(2)在main()方法中使用异常处理语句进行异常处理。
(3)在程序中,自定义对应输入负数的异常类(EcDef)。
(4)运行时接受参数 java EcmDef 20 10 //args[0]=“20” args[1]=“10”
(5)Interger类的static方法parseInt(String s)将s转换成对应的int值。
如:int a=Interger.parseInt(“314”); //a=314;

 */
public class EcmDef {
    public static void main(String[] args) {
        try {
            int i = Integer.parseInt(args[0]);
            int j = Integer.parseInt(args[1]);
            int result = ecm(i, j);
            System.out.println(result);
        }catch(NumberFormatException e){
            System.out.println("数据类型不一致");
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("缺少命令行参数");
        }catch(ArithmeticException e){
            System.out.println("0不能做除数");
        }catch(MyException e){
            System.out.println(e.getMessage());
        }
    }
    public static int ecm(int i,int j) throws MyException {
        if(i < 0 || j < 0){
            throw new MyException("不能输入负数哦!");
        }
        return i / j;
    }
}
EcmDef.java
package com.lzh.exception_exer;

// 自定义的异常类
public class MyException extends Exception{
    static final long serialVersionUID = -338751699324229948L;
    public MyException(){

    }
    public MyException(String message){
        super(message);
    }

}
MyException.java

11 - 异常处理五个关键字总结

/*

throw 和 throws 的区别?

throw 表示抛出一个异常类的对象,生成异常对象的过程,声明在方法体内。

throws 属于异常处理的一种机制,声明在方法声明处。

*/

 

posted @ 2020-06-06 14:14  赖正华  阅读(135)  评论(0编辑  收藏  举报