JAVA基础知识(六)——异常处理

一、异常概述与异常体系结构

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

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

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

    • Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError和OOM(OutOfMemoryError)。一般不编写针对性的代码进行处理。
    • Exception:其他因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。例如:
      • 空指针访问
      • 视图读取不存在的文件
      • 网络连接中断
      • 数组角标越界
    • 举例:
        //1.栈溢出 Exception in thread "main" java.lang.StackOverflowError
        main(args);
        //2.堆溢出 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        Integer[] arr= new Integer[1024*1024*1024];
    
    • 对于这些错误,一般有两种解决方法:一是遇到错误就终止程序的运行。另一种方法是由程序员在编写程序时,就考虑到错误的检测、错误消息的提示,以及错误的处理。

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

      • 分类:编译时异常运行时异常
  • 结构图(面试题:常见的异常有哪些?)
    在这里插入图片描述

二、常见异常

FileNotFoundException、IOExcpetion、ClassNotFoundException、ClassCastException、NullPointerException。

三、异常处理机制一:try-catch-finally

  • 在编写程序时,经常要在可能出现错误的地方加上检测的代码,如进行x/y运算时,要检测分母为0,数据为空,输入的不是数据而是字符等。过多的if-else分支会导致程序的代码加长、臃肿,可读性差。因此采用异常处理机制。
  • Java异常处理
    Java采用的异常处理机制,是将异常处理的程序代码集中在一起,与正常的程序代码分开,使得程序简洁、优雅,并易于维护。
  • try-catch-finally
    (1)finally是可选的
    (2)使用try将可能出现异常代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型去catch中进行匹配
    (3)一旦try中的异常匹配到某一个catch时,就进入catch中进行异常的处理,一旦处理完成,
    就跳出当前的try-catch结构(没有写finally的情况),继续执行其后的代码
    (4)catch中的异常类型如果没有子父类关系,则谁声明在上,谁声明在下无所谓。
    catch中的异常类型满足子父类的关系,则要求子类一定声明在父类上面。否则报错。
    (5) 常用的异常对象处理的方式: one:String getMessage(); two:printStackTrace()
    (6) 在try结构中声明的变量,再出了try结构以后,就不能再被调用
    (7) try-catch-finally结构可以嵌套。
  • 示例:
import org.junit.Test;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
/**
 * 一、异常的处理: 抓抛模型
 * 过程一: “抛”, 程序在正常执行过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象。并将此对象抛出。
 *              一旦抛出对象以后,其后的代码就不再执行。
 *
 *         关于异常对象的产生(1)系统自动生成的异常对象
 *                          (2)手动的生成一个异常对象,并抛出 throw
 *
 * 过程二: “抓”, 可以理解为异常的处理方式 (1)try-catch-finally (2)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) 常用的异常对象处理的方式: one:String getMessage();  two:printStackTrace()
 *        (6) 在try结构中声明的变量,再出了try结构以后,就不能再被调用
 *        (7) try-catch-finally结构可以嵌套。
 *
 *     体会1:使用try-catch-finally处理编译时异常,使得程序在编译时就不再报错,但是运行时仍可能报错。
 *           相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现。
 *     体会2:开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常进行编写try-catch-finally了
 *           针对于编译时异常,我们说一定要考虑异常的处理。
 */
public class TryCatchTest {
    @Test
    public void demo1(){
        String str = "hello";
        try {
            Integer.parseInt(str);
            System.out.println("转换结束...");
        }catch (NumberFormatException e){
//            System.err.println("出现数值转换异常: NumberFormatException");
 
            //String getMessage();
            String message = e.getMessage();
            System.out.println(message); //For input string: "hello"
 
            e.printStackTrace();
            /*
            java.lang.NumberFormatException: For input string: "hello"
            at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
            at java.lang.Integer.parseInt(Integer.java:580)
            at java.lang.Integer.parseInt(Integer.java:615)
            at com.notes._1Java基础编程._7异常处理._3异常的处理方式._3异常的处理方式.demo1(_3异常的处理方式.java:42)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
            at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
            at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
            at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
            at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
            at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
            at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
            at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
            at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
            at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
            at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
            at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
            at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
            at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
             */
        }
 
//        System.out.println("执行结束...");
    }
 
    @Test
    public void demo2(){
        try {
            FileInputStream fis = new FileInputStream("E:\\附件\\file\\txt\\hello.txt");
            int index = ' ';
            while ((index = fis.read()) != -1){
                System.out.print((char)index);
            }
            fis.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
 
import org.junit.Test;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
/**
 * try-catch-finally的使用
 * 1、finally是可选的
 * 2、finally中声明的是一定会执行的代码。即使catch中又出现异常了、try中有return语句、catch中有return语句等情况。
 * 3、像数据库连接、输入输出流、网络编程socket连接等资源,JVM是不能自动回收的,我们需要手动的进行资源的释放。此时资源的释放,就需要声明在finally中。
 *
 */
public class FinallyTest {
    @Test
    public void demo1(){
        try {
            int a = 10 / 0;
            System.out.println(a);
        }catch (ArithmeticException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("执行结束");
        }
    }
 
    //finally中声明的是一定会执行的代码。即使catch中又出现异常了、try中有return语句、catch中有return语句等情况。
    @Test
    public void demo2(){
        int a = method();
        System.out.println(a);
    }
 
    public int method(){
        try {
            int a = 10 / 0;
            System.out.println(a);
            return 1;
        }catch (ArithmeticException e){
            e.printStackTrace();
            return 2;
        }catch (Exception e){
            e.printStackTrace();
            return 3;
        }finally {
            System.out.println("执行结束");
//            return 4;
        }
    }
 
    //像数据库连接、输入输出流、网络编程socket连接等资源,JVM是不能自动回收的,我们需要手动的进行资源的释放。此时资源的释放,就需要声明在finally中。
    @Test
    public void demo3(){
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("hello.txt");
            int index = ' ';
            while ((index = fis.read()) != -1){
                System.out.print((char)index);
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (fis != null){ //可能会报空指针异常
                    fis.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
 
  • finally
    • finally是可选的
    • finally中声明的是一定会被执行的代码。即使catch中又出现了异常了,try中有return语句,catch有return语句等情况。
    • 像数据库连接、输入输出流、网络编程Socker等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的释放。此时的资源释放,就需要声明在finally中。
    • 示例代码:(重点是return返回值问题)
    public static void main(String[] args) {
        int returnValue = finallyReturnTest();
        System.out.println("returnValue = " + returnValue);
    }

    public static int finallyReturnTest() {
        int m = 0 ;
        try{
            m = 8/0;
            return m; 
        }catch(ArithmeticException e) {
            return 1; //返回return 1
        } finally {
            System.out.println("测试finllay");
            //return 3;//如果打开注释返回 return 3
        }
        //return m;
    }

四、异常处理机制二:throws

import org.junit.Test;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
/**
 * 异常的处理方式二: throws + 异常类型
 *
 * 1、"throws + 异常类型" 声明在方法的声明处。指明此方法执行时,可能会抛出的异常类型。
 *    一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出。
 *    异常代码后续的代码,就不再执行。
 *
 * 2、体会:try-catch-finally 真正的将异常给处理掉了
 *         throws的方式只是将异常抛给了方法的调用者,并没有真正将异常处理掉。
 *
 * 3、开发中如何选择使用try-catch-finally 还是使用throws
 *    (1)如果父类被重写的方法没有用throws方式处理异常,则子类重写的方法也不能使用throws,意味着如果子类重写的方法中有异常,必须使用try-catch-finally方式处理。
 *    (2)执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的,我们建议这几个方法使用throws的方式进行处理,而执行的方法a可以考虑使用try-catch-finally方式进行处理。
 */
public class ThrowsTest {
 
    public void demo1() throws FileNotFoundException, IOException{
        FileInputStream fis = new FileInputStream("hello.txt");
        int index = ' ';
        while ((index = fis.read()) != -1){
            System.out.print((char)index);
        }
        fis.close();
    }
 
    public void demo2() throws IOException{
        demo1();
    }
 
    @Test
    public void demo3(){
        try {
            demo2();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
  • 重写方法声明抛出异常的原则
    • 子类重写方法抛出异常的类型,不大于父类被重写方法抛出异常的类型
    • 如果子类重写方法抛出异常的类型,大于父类被重写方法抛出异常的类型,进行try-catch后,可能捕捉不到子类抛出的异常,程序会报错终止

public class JavaDemoException {

    public static void main(String[] args) {
        Car car = new Bar();
        try {
            car.startCar();//编译时 按照父类抛出的异常的进行编译,所有子类重写的方法抛出的异常不能大于父类抛出的异常
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class Car {
     //启动车辆
    public void startCar() throws FileNotFoundException {

    }
}

class Bar extends Car {
    public void startCar() throws IOException { //报错

    }
}

五、手动抛出异常:throw

public class _5手动抛出异常对象 {
    public static void main(String[] args) {
        Student student = new Student();
        try {
            student.register(-1001);
            System.out.println(student);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
 
    }
}
 
class Student{
    private int id;
 
    public void register(int id) throws Exception {
        if (id > 0){
            this.id = id;
        }else {
//            System.out.println("输入的数据非法: " + id);
            //手动抛出异常对象
//            throw new RuntimeException("输入的数据非法 id: " + id); //运行时异常
            throw new Exception("输入的数据非法 id: " + id);
        }
    }
 
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                '}';
    }
}
  • Java异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出,也可根据需要使用人工创建并抛出。

    • 首先要生成异常类对象,然后通过throw语句实现抛出操作(提交给Java运行环境)。
    IOException e = new IOException();
    throw e;
    
    • 可以抛出的异常必须是Throwable或其子类的实例。下面的语句在编译时将会产生语法错误:
    throw new String("want to throw");
    

六、用户自定义异常类

  • 自定义异常类的注意点
    • 一般地,用户自定义异常类都是RuntimeException的子类。
    • 自定义异常类通常需要编写几个重载的构造器。
    • 自定义异常需要提供serialVersionUID
    • 自定义的异常通过throw抛出。
    • 自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类型。
    • 用户自定义异常类MyException,用于描述数据取值范围错误信息。用户自己的异常类必须继承现有的异常类。
class MyException extends Exception {
    static final long serialVersionUID = 13465653435L;
    private int idnumber;
    public MyException(String message, int id) {
        super(message);
        this.idnumber = id;
    }
    public int getId() {
        return idnumber;
    }
}
public class MyExpTest {
    public void regist(int num) throws MyException {
        if (num < 0)
            throw new MyException("人数为负值,不合理", 3);
        else
            System.out.println("登记人数" + num);
    }
    public void manager() {
        try {
            regist(100);
        } catch (MyException e) {
            System.out.print("登记失败,出错种类" + e.getId());
        }
        System.out.print("本次登记操作结束");
    }
    public static void main(String args[]) {
        MyExpTest t = new MyExpTest();
        t.manager();
    }
}
  • 例题:

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

  • 如果父类中被重写的的方法没有throws方式处理异常,则子类重写的方法也不能使用throws,意味着如果子类重写的方法中有异常,必须使用try-catch-finally方式处理
    public static void main(String[] args) {
        Car car = new Bar();
        try {
            car.startCar();//编译时 按照父类抛出的异常的进行编译,所有子类重写的方法抛出的异常不能大于父类抛出的异常
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class Car {
     //启动车辆
    public void startCar()  {
    }
}

class Bar extends Car {
    public void startCar() throws FileNotFoundException { //报错

    }
}

在这里插入图片描述

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

    public static void main(String[] args) {
       try {
           methodA();
       } catch (RuntimeException e) {
           System.out.println(e.getMessage());
       }
       methodB();

    }

    static void methodA() {
        try {
            System.out.println("进入方法A");
            throw new RuntimeException("制造异常");
        } finally {
            System.out.println("用A的方法的finally");
        }

    }
    static void methodB() {
        try {
            System.out.println("进入方法B");
            return;
        } finally {
            System.out.println("用B的方法的finally");
        }

    }
/*    进入方法A
            用A的方法的finally
    制造异常
            进入方法B
    用B的方法的finally*/

}

八、如何看待代码中的编译时异常和运行时异常?

  • 体会1:使用try-catch-finally处理编译时异常,是得程序在编译时就不再报错,但是运行时仍可能报错。相当于我们使用try-catch-finally将一个编译时可能出现得异常,延迟到运行时出现。
  • 体会2:开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally了。
  • 针对于编译时异常,我们说一定要考虑异常的处理。

九、throw和throws区别

  • throw表示抛出一个异常类的对象,生成异常对象的过程。声明在方法体内。
  • throws属于异常处理的一种方式,声明在方法的声明处。

十、总结:异常处理5个关键字

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值