Java异常简介

一、概念及体系结构

1.1异常的概念

异常:程序执行中发生的不正常情况称为异常

1.2异常处理的必要性:

任何程序都可能存在大量未知问题、错误;如果不对这些问题进行正确处理,则可能导致JVM停止运行,意味着后面代码不会继续执行进而造成不必要的损失

1.3异常分类

  • Throwable(异常的父类):可抛出的,一切错误或异常的父类,位于java.lang 包中
    • Error(错误):JVM、硬件、指向逻辑错误,不能手动处理(无法通过程序解决)
    • Exception(异常):程序在运行和配置中产生的问题,可处理
      • RuntimeException(运行时异常):程序运行期间出现的异常,可处理,可不处理
        • 编译器不要求强制处置的异常
        • 一般是由程序逻辑错误引起的,程序可以通过修改逻辑代码规避
        • java.lang.RuntimeException类及它的子类都是运行时异常
        • 对于这类异常,可以不作处理,因为这类异常很普遍,若全处理可能会对程序的可读性和运行效率产生影响
        • 举例:空指针异常 类转换异常 数组下标越界异常 下标越界异常 输入异常 …
      • Exception:编译时异常,受查异常,必须处理
        • 编译器要求必须处置的异常;
        • 除了RuntimeException及其子类以外,其他的Exception类及其子类都属于编译时异常;
        • 编译器要求Java程序必须捕获或声明所有编译时异常;
        • 对于这类异常,如果程序不处理,可能会带来意想不到的结果
        • ParseException …
public class Demo {
    public static void main(String[] args) {
        //test1();
        //test2();
        //test3();
        //test4();
        //test5();
        //test6();
    }

    //OutOfMemoryError
    public static void test1() {
        int[] arr = new int[1024*1024*1024]; //int 4GB
        System.out.println("************************");
    }

    //StackOverflowError
    public static void test2() {
        test1();//递归
    }

    //ArithmeticException
    public static void test3() {
        int a = 10/0;
    }

    //NullPointerException
    public static void test4() {
        String str = null;
        System.out.println(str.length());
    }

    //ArrayIndexOutOfBoundsException
    public static void test5() {
        int[] arr = new int[5];
        arr[5] = 100;
    }

    //ClassCastException
    public static void test6() {
        Object obj = new Object();
        String str = (String)obj;
    }
}

异常的产生

  • 自动抛出异常:当程序在运行时遇到不符合规范的代码或结果时,会产生异常
  • 手动抛出异常:语法:throw new异常类型("实际参数");
    • 产生异常结果:相当于遇到return语句,导致程序因异常而停止

1.4异常的处理(异常处理机制)

  • 如果正确的处理了异常那么就不会终止程序的运行
1.4.1异常的捕获try-catch-finally
try{
	//可能产生异常的代码
} catch(要捕获的异常类型1 e ){
	//当产生要 捕获的异常类型1 型异常时的处置措施
} catch(要捕获的异常类型2 e ){
	//当产生 要捕获的异常类型2 型异常时的处置措施
}finally{
	//无论是否发生异常,都无条件执行的语句
}

try

  • 捕获异常的第一步是用try{…}语句块选定捕获异常的范围,将可能出现异常的代码放在try语句块中。

catch

  1. catch中异常类型必须是try出现的异常,否则相当于没有处理
  2. catch可以有多个,但是顺序要从子(小)到父(大),父类异常在最后
  3. catch也可以捕获到Exception,这样所有的异常都会被捕获到

getMessage()获取异常信息,返回字符串;

printStackTrace()获取异常类名和异常信息,以及异常出现在程序中的位置,返回值void

finally

  1. 不论在try代码块中是否发生了异常事件,catch语句是否执行,catch语句是否有异常,catch语句中是否有returnfinally块中的语句都会被执行,一般用于释放等必须要做的事
  2. 无论在try中还是在catch中使用return ,finally都会执行。在执行时,是return语句先把返回值写入内存中,然后停下来等待finally语句块执行完,return再执行后面的一段
  3. finally语句是任选的
1.4.2throws throw

throws(被动)

语法:

[修饰符] 返回值类型 方法名(参数列表) throws 异常类型1, 异常类型2 {
    
}

应用场景: 当定义方法时候,当前方法中还不知道如果解决值给异常的时候,就将异常声明出去交给方法的调用者,声明异常一般是在编译期异常

throw(主动)

语法:

[修饰符] 返回值类型 方法名(参数列表)  {
    throw new 异常对象
}

应用场景:在方法内部,方法满足某种不合理的条件的时候,主动向调用者抛出异常

注意:在方法的内部抛出异常,如果是编译期异常,通常要声明出去

案例:

public class Demo02 {
    public static void main(String[] args) {
        try {
            div(100, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int div(int a, int b) throws Exception {
        return a / b;
    }
}

public class Demo01{
	public static void main(String[] args) {
         try {
             read();
         } catch (IOException e) {
             e.printStackTrace();
         }
	}
    
    public static void read() throws IOException {
        //创建Properties
        Properties prop = new Properties();
        //加载配置文件
        prop.load(new FileInputStream("jdbc.properties"));
        //获取配置文件中key对应的value
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");

        System.out.println(username);
        System.out.println(password);
    }
}
  • Java异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出,也可根据需要使用人工创建并抛出。

  • 首先要生成异常类对象,然后通过throw语句实现抛出操作(提交给Java运行环境)

public class Demo{
    public static void main(String[] args) {
        try {
            div(100, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int div(int a, int b) throws Exception {
        if(b == 0) {
            throw new Exception("除数为0");
        }
        return a / b;
    }
}

二、自定义异常类

JDK提供的异常有限 有些不符合开发的处理 所有自定义异常

自定义异常一般配合自己的代码使用

  • 自定义异常类继承Exception或它的子类
  • 自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类型
    • 子类不能抛出比父类更大的异常
public class MyException extends Exception {
	//构造方法
	public MyException(String msg) {
        //Exception有自己的异常处理方式直接使用父类的
		super(msg);//调用父类的构造方法
	}
}

public class Demo {
    public static void main(String[] args) {
        try {
            div(100, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int div(int a, int b) throws MyException {
        if(b == 0) {
            throw new MyException("除数为0");
        }
        return a / b;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值