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

 异常:导致执行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);
	}
	
}
发布了16 篇原创文章 · 获赞 0 · 访问量 224

猜你喜欢

转载自blog.csdn.net/LinDadaxia/article/details/105492613