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();
	}
}

输出结果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值