Java异常处理——Exception和RuntimeException

Exception是检查型异常,在程序中必须使用try...catch进行处理;

RuntimeException是非检查型异常,例如NumberFormatException,可以不使用try...catch进行处理,

但是如果产生异常,则异常将由JVM进行处理;

RuntimeException用法:

package m01d01;

public class Exception01 {

	public static void testRuntimeException() throws RuntimeException{
		throw new RuntimeException("运行时异常");
	}
	
	public static void testException() throws Exception{
		throw new Exception("编译时异常");
	}
	
	public static void main(String[] args) {
		testRuntimeException();
		

	}
}

可以看见,运行时异常可以不用 try...catch进行处理,仍然能运行成功;

结果为:

但是Exception必须要捕获,否则编译就会报错:

使用try...catch进行处理后:

package m01d01;

public class Exception01 {

	public static void testRuntimeException() throws RuntimeException{
		throw new RuntimeException("运行时异常");
	}
	
	public static void testException() throws Exception{
		throw new Exception("编译时异常");
	}
	
	public static void main(String[] args) {
		
		try {
			testException();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		testRuntimeException();
	}
}

输出结果:

 

猜你喜欢

转载自blog.csdn.net/qq_37084904/article/details/85550220