Java学习笔记:异常

一、概述:

异常指在程序运行时,遇到到的各种不正常的状况。

Java程序在运行时可能遇到的异常可分为两类

  1. Exception
    ①编译时异常
    ②运行时异常

  2. Error
    比Exception更加致命,是Java虚拟机无法解决的严重问题。大多与程序员无关。

Error和Exception的区别是Error是程序无法控制和处理的,当出现这种异常时,Java虚拟机会终止线程;而Exception通常是可以被程序处理的。

异常体系结构:
在这里插入图片描述

二、运行时异常举例

  1. ArithmeticException (算术运算异常)
		int a = 10;
        int b = 0;
        System.out.println(a/b);
  1. NullPointerException (空指针异常)
		int[] array = null;
        System.out.println(array[0]);
		String str = null;
        System.out.println(str.charAt(0));
  1. ArrayIndexOutOfBoundsException (数组下标越界)
		int[] array = new int[5];
        System.out.println(array[5]);

三、异常处理

  1. try - catch - finally
    将可能出现异常的代码用try代码块装起来,与其余不会出现异常的代码隔离开。
        try{  
        //监控区域(此处可能出现异常)
        }catch (异常类型1 变量名1){//例:(NumberFormatException e)
            //捕获异常
            //处理异常1的方法
        }catch (异常类型2 变量名2){
        	//处理异常2的方法
        }catch (异常类型3 变量名3){
        	//处理异常3的方法
        	/*
        	可以包含多个catch
        	但要捕获多个异常时,必须要从小到大的捕获
			*/
        }finally {  
        //一定会执行的代码
        //作用:处理善后工作,可以不写
        }
    }

快捷键: Ctrl + Alt + T => try/catch/finally

try {
            System.out.println(a/b);
        } catch (Exception e) {  //可以在这里面加入自己的程序
            e.printStackTrace();  //打印错误的栈信息
        } finally {
        }
  1. throws + 异常类型(可能会出现的异常)
    只能写在方法的声明处。当方法体执行时,出现异常则会在异常代码处生成一个异常类的对象,此对象如果满足throws后异常类型是,就会被抛出(抛出不代表解决此异常,最后还是要用try - catch - finally方法来解决异常)。而抛出后的代码将不被执行
public static void main(String[] args) {
        test2();
    }

   public static void test1() throws ArithmeticException,RuntimeException{
       int a = 10;
       int b = 0;
        System.out.println(a/b);
       System.out.println("hhh");  //异常抛出后的代码不执行
    }

    public static void test2(){
        try {
            test1();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            System.out.println("haha");
        }
    }

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值