Java高级重点知识点-17-异常

异常

指的是程序在执行过程中,出现的非正常的情况,最终会导致JVM的非正常停止。Java处 理异常的方式是中断处理。

  1. 异常体系

异常的根类是 java.lang.Throwable,,其下有两个子类:java.lang.Error 与 java.lang.Exception。
在这里插入图片描述
在这里插入图片描述

  1. 异常分类
  • 编译时期异常:checked异常。在编译时期,就会检查,如果没有处理异常,则编译失败。(如日期格式化异常)
  • 运行时期异常:runtime异常。在运行时期,检查异常.在编译时期,运行异常不会编译器检测(不报错)。(如数学异常)

在这里插入图片描述

异常处理

Java异常处理的五个关键字:try、catch、finally、throw、throws

  1. 抛出异常throw

使用格式:

throw new 异常类名(参数);
public class ExceptionDemo {

    public static int getElement(int[] arr , int index){
        if (index < 0 || index >= arr.length){
            throw new ArrayIndexOutOfBoundsException("数组下标越界啦!");
        }

        int element = arr[index];
        return element;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int index = 5;
        int element = getElement(arr, index);
        System.out.println(element);
        System.out.println("over");
    }
}

在这里插入图片描述

  1. 声明异常throws

使用格式:

修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2…{ }
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionDemo {
    public static void findFile(String file) throws FileNotFoundException,IOException{
        if (!file.equals("a.txt")){
            throw new FileNotFoundException("找不到文件");
        }

        int index = file.lastIndexOf(".");
        String prefix = file.substring(index);
        if (prefix.equals(".txt")){
            System.out.println("文件格式正确");
        }else {
            throw new IOException("文件格式不正确");
        }
    }

    public static void main(String[] args) throws IOException {
        String file = "a.txt";
        findFile(file);
        System.out.println("over");
    }
}

在这里插入图片描述

  1. 捕获异常try…catch

Java中对异常有针对性的语句进行捕获,可以对出现的异常进行指定方式的处理。

try{
	编写可能会出现异常的代码
}catch(异常类型 e){
	处理异常的代码
	//记录日志/打印异常信息/继续抛出异常
}
  • 该方法不处理,而是声明抛出,由该方法的调用者来处理(throws)。
  • 在方法中使用try-catch的语句块来处理异常。
import java.io.IOException;

public class ExceptionDemo {
    public static void findFile(String file) throws IOException{
        int index = file.lastIndexOf(".");
        String prefix = file.substring(index);
        if (prefix.equals(".txt")){
            System.out.println("文件格式正确");
        }else {
            throw new IOException("文件格式不正确");
        }
    }

    public static void main(String[] args){
        String file = "a.html";
        try {
            findFile(file);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        System.out.println("over");
    }
}

在这里插入图片描述

Throwable类中定义了一些查看方法:

  • public String getMessage() :获取异常的描述信息,原因(提示给用户的时候,就提示错误原因。
  • public String toString() :获取异常的类型和异常描述信息(不用)。
  • public void printStackTrace() :打印异常的跟踪栈信息并输出到控制台。
  1. finally 代码块

有一些特定的代码无论异常是否发生,都需要执行。因此我们就会使用finally关键字来解决这个问题

import java.io.IOException;

public class ExceptionDemo {
    public static void findFile(String file) throws IOException{
        int index = file.lastIndexOf(".");
        String prefix = file.substring(index);
        if (prefix.equals(".txt")){
            System.out.println("文件格式正确");
        }else {
            throw new IOException("文件格式不正确");
        }
    }

    public static void main(String[] args){
        String file = "a.html";
        try {
            findFile(file);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            System.out.println("不管出不出现异常都要执行!");
        }
        System.out.println("over");
    }
}

在这里插入图片描述

  1. 多个异常进行捕获的方式:
  • 多个异常分别处理。
  • 多个异常一次捕获,多次处理。
  • 多个异常一次捕获一次处理。

注意:

  • 运行时异常被抛出可以不处理。即不捕获也不声明抛出。
  • 如果finally有return语句,永远返回finally中的结果,避免该情况.
  • 如果父类抛出了多个异常,子类重写父类方法时,抛出和父类相同的异常或者是父类异常的子类或者不抛出异常。
  • 父类方法没有抛出异常,子类重写父类该方法时也不可抛出异常。此时子类产生该异常,只能捕获处理,不能声明抛出

自定义异常

异常类如何定义:

  1. 自定义一个编译期异常: 自定义类 并继承于 java.lang.Exception 。
    代码示例:
	// 业务逻辑异常
public class MyException extends Exception {
	/**
	* 空参构造
	*/
	public MyException () {
	}
	/**
	*
	* @param message 表示异常提示
	*/
	public MyException (String message) {
		super(message);
	}
}
  1. 自定义一个运行时期的异常类:自定义类 并继承于 java.lang.RuntimeException 。
public class MyException extends RuntimeException {
    /**
     * 空参构造
     */
    public MyException () {
    }

    /**
     *
     * @param message 表示异常提示
     */
    public MyException (String message) {
        super(message);
    }
}

总的来说就是,继承异常类Exception或者RuntimeException,重写空参构造方法和有参构造方法。

欢迎java热爱者了解文章,作者将会持续更新中,期待各位友友的关注和收藏,另外对编程感兴趣的友友们可以加以下群共同学习。群号:127871664

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿胡爱编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值