Java:Error(错误)和Exception(异常)

x33g5p2x  于2021-09-09 转载在 Java  
字(0.8k)|赞(0)|评价(0)|浏览(343)

0.前言

Throwable: 有两个重要的子类:Exception(异常)和 Error(错误),二者都是 Java 异常处理的重要子类,各自都包含大量子类。

1. 异常和错误的区别:

异常能被程序本身可以处理,错误是无法处理。

2. error

Error 是底层的,程序本身不能处理的系统错误, 如内存溢出, 虚拟机栈溢出等。
OutOfMemoryError
StackOverflowError

3. Exception

3.1 非RuntimeExcption

这种异常必须由程序员手动处理,否则不通过编译。
一般写的时候,编辑器会提示报错,提示使用try catch处理,或者抛出。
IOException

3.2 RuntimeException

RuntimeException在写代码的时候,编辑器不会提示报错
数组越界,空指针异常,类型转换异常,算数异常

4. 异常的捕获处理

一种方式是交由程序员使用try catch捕获处理,不会中断程序
一种方式是交由JVM处理,中断程序,控制台输出异常信息

public class ExceptionDemo {
	
	//运行时异常,除数为0 
	//jvm处理,程序中断,并把异常信息输出到屏幕上
	public static int divFun(int a, int b) {
		int res = 0;
		res = a/b;	
		return res;
	}
	//运行时异常,除数为0
	//捕获处理,程序不中断
	public static int divFun_plus(int a, int b) {
		int res = 0;
		try{
		res = a/b;
		}catch(Exception e) {
			System.out.println("算数异常!!!");
		}
		return res;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

// System.out.println(divFun(8, 0));
		System.out.println(divFun_plus(8, 0));

	}

}

在这里插入图片描述

在这里插入图片描述

相关文章

微信公众号

最新文章

更多