检查时异常和运行时异常区别

本文深入探讨Java中的异常处理机制,包括异常的定义、分类及处理方式。通过具体代码示例,详细讲解了try-catch-finally语句的使用,以及如何通过catch块捕获不同类型的异常,确保程序的稳定性和健壮性。

 异常:导致执行java程序无法顺利执行的错误就叫做异常。(当程序中出现异常时,异常出现后下面的代码将不再执行)

public class Test {
	public static void main(String[] args) {
		int age=12;
		System.out.println(age/3);
		System.out.println(age/0);
		System.out.println(age/2);
	}
	
}
 结果:Exception in thread "main" 4  //第一个输出的结果
            java.lang.ArithmeticException: / by zero//指出异常
                                                     at sunny/com.jd.text.Test.main(Test.java:7)//异常所在位置


 异常分类:Error(不需要处理) || Exception(需要处理)
         Exception分为检查时异常和运行时异常

 两类异常
                                                  父类                                                     是否需要显式处理
 检查时异常:  除了父类为RuntimeException的其他异常                      必须要显式处理(不处理无法执行代码)
 运行时异常:   直接或间接继承RuntimeException                                        不需要

 异常处理方式:try-catch-finally;throw与throws
 本次探讨较为简单的try-catch-finally;

public class Test {
	public static void main(String[] args) {
		int age=12;
		try {//先进行尝试执行看有无异常
			System.out.println(age/0);
		}catch(ArithmeticException e){//若符合catch变量取值中的异常类型时进入语句块进行操作
			System.out.println(e);
		}finally{//无论怎样都执行
            System.out.println("都执行");
        }
		
		System.out.println(age);
	}
	
}
执行结果:java.lang.ArithmeticException: / by zero
         12
         都执行

同时可以有多个catch语句块;范围要从下到大

public class Test {
	public static void main(String[] args) {
		int age=12;
		try {
			System.out.println(age/0);
		}catch(ArithmeticException e){
			System.out.println(e);
		}catch(RuntimeException e){
			System.out.println(e);
		}catch(Exception e){
			System.out.println(e);
		}finally{
            System.out.println("都执行");
        }
		
		System.out.println(age);
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值