13

发布时间 2023-11-29 11:16:14作者: 拾光师
title: 异常
author: ZH
date: 2020-11-10 18:14:23
tags: 
	- java基础
categories: java基础

异常

当异常发生时,该线程会暂停,逐层退出方法调用,直到遇到异常处理器,异常处理器可以catch到异常对象,进行相应的处理

异常的类型

Throwable有两个子类,一个是Error错误,一个是Exception异常

Throwable包含了其线程创建时线程执行堆栈的快照,使用printStackTrace()等接口用于获取堆栈跟踪数据等信息

  • Error通常表示的是java内部错误,如内存溢出等,不能在编程的层面上解决Error,如VirtualMachineError虚拟机运行错误、NoClassDefFoundError类定义错误、OutOfMemoryError内存不足错误、StackOverflowError栈溢出错误
  • Exception则表示异常,程序本身可以捕获并且可以处理的异常,分为unchecked异常和checked异常
    • unchecked异常,运行时异常,是由于编程时犯错导致的,继承的是RuntimeException,如ClassCastException(类型转换异常)、NullPointerException(空指针异常)、ArithmeticException(算术异常)、IndexOutOfBoundsException(数组下标越界异常)、IllegalArgumentException(参数异常)等
    • checked异常,编译时异常,是由于编程与环境互动造成程序出错,如果出现此类异常,需要手动捕获处理,否则不能通过编译,如IOException、MalformedURLException、ClassNotFoundException等

throw和throws

throw关键字用在方法内部,只能用于抛出一种异常,用来抛出一种异常,用于抛出方法或代码块中的异常。

throws关键字用在方法声明上,可以抛出多个异常,用来标识该方法可能抛出的异常列表

finally

finally用来进行扫尾,有时候会遇到catch中进行return,这时候finally会在return前执行

public class TestExceptionn {
    public int f0(){
        int i =0;
        try{
            throw new RuntimeException();
        } catch (Exception e){
            i = 1;
            // 此时会记录下该值,不会立马返回,执行完finally之后在返回该值
            return i;
        } finally {
            i = 2;
        }
    }

    public int f(){
        int i =0;
        try{
            throw new RuntimeException();
        } catch (Exception e){
            i = 1;
            return i;
        } finally {
            i = 2;
            // 这里会返回最后一次的return
            return i;
        }
    }
    public static void main(String[] args) {
        TestExceptionn tst = new TestExceptionn();
        // 输出1
        System.out.println(tst.f0());
        // 输出2
        System.out.println(tst.f());
    }
}