初识 Java 异常(异常的概念、捕获、主动抛出)

异常

在Java中,将程序执行过程中发生的不正常行为称为异常。

分类: 检查性异常、运行时异常、错误

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

Java 把异常当做对象来处理,并定义一个基类 java.lang。Throwable 作为所有异常的超类 。(最顶层的类)

关键字: try 、catth 、finally 、 throw 、throws

(一)异常的捕获:

代码举例:

public class Demo01 {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;

       try {  //try监控区域
            System.out.println( a/b );
        } catch (Exception e) {  // catch 想要捕获的异常类型
            System.out.println("Error");
        } finally { //处理善后工作,也可以不要  通常在finally中处理IO、资源及关闭等操作,此处一定会执行
            System.out.println("finally");
        }    

使用快捷键生成

   //可以使用Ctrl + Alt + t 快速生成 try catch finally语句,选中要监控的语句,按下快捷键,选择try catch finally
        try {
            System.out.println( a/b );
        } catch (Exception e) {
            e.printStackTrace(); //此处可以打印错误的栈信息
        } finally {
            System.out.println("finally");
        }
    }
}

try catch 语句与 if else 语句类似,允许嵌套,但范围应该按照从小到大的顺序

 public static void main(String[] args) {
        int a = 10;
        int b = 0;  
	try {
                System.out.println( a/b );
            } catch (Exception t) {
                System.out.println("Exception");
            } catch (Error m) {
                System.out.println("Error");
            } catch (Throwable n) {
                System.out.println("Throwable");
            }
            finally {
                System.out.println("finally");
            }
	   }
 }
(二)主动抛出异常 :
  1. throw :主动在抛出异常,通常用在方法中
public class test02 {
    public static void main(String[] args) {
        int a = 20;
        int b = 0;
        new test02().div(a,b);
    }
    public  void div(int a,int b) {
        if( b== 0) {
            throw new ArithmeticException();//主动抛出异常,一般用在方法中
        }
    }
}

运行结果
在这里插入图片描述

  1. throws : 如果在方法中处理不了该异常,可以使用 throws 关键字将该异常抛出到更高一级中处理
public class test02 {
    public static void main(String[] args) {
        int a = 20;
        int b = 0;
        try {            //此处捕获 div 方法中抛出的异常,可以使程序不终止继续运行,而后在这个语句中处理该异常
            new test02().div(a,b);
        } catch (ArithmeticException e) {
            System.out.println("异常");
        } finally {
            System.out.println("finally");
        }
        System.out.println("继续执行");
    }

    public  void div(int a,int b) throws ArithmeticException {
        if( b== 0) {
            throw new ArithmeticException();//throw关键字:主动抛出异常,一般用在方法中
        }
    }
}

运行结果:
在这里插入图片描述

可以看到 最后一条语句被执行了,说明异常被捕获了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值