Java编译时异常和运行时异常

一 什么是编译时异常,什么是运行时异常

运行时异常可以通过改变程序避免这种情况发生,比如,除数为0异常,可以先判断除数是否是0,如果是0,则结束此程序。从继承上来看,只要是继承RunTimeException类的,都是运行时异常,其它为编译时异常。


二编译时异常和运行时异常的区别

使用抛出处理方式处理异常时,对于编译时异常,当函数内部有异常抛出,该函数必须声明,调用者也必须处理运行时异常则不一定要声明,调用者也不必处理

ArithmeticException运行时异常
public class Test {
	public static  int a=0;
	public static void main(String[] args){
		// TODO Auto-generated method stub
          a = test(4,0);
	}
	public static int test(int a,int b){
		if(b==0){
		  throw new ArithmeticException();
		}
		return a/b;
	}
}
打印结果:
Exception in thread "main" java.lang.ArithmeticException
at testexception.Test.test(Test.java:11)
at testexception.Test.main(Test.java:7)

从上面代码中可以看出,运行时异常可以不需声明异常


下面是编译时异常,TimeOutException,超时连接异常,模拟当i大于10时,即超过10秒,抛出连接超时异常。
package testexception;

import java.util.concurrent.TimeoutException;

public class Test {
	public static void main(String[] args)throws TimeoutException{
		// TODO Auto-generated method stub
         test(11);
	}
	public static void test(int i) throws TimeoutException{
		if(i>10)
		  throw new TimeoutException();
		System.out.println("连接没有超时");
	}
}

打印结果:

Exception in thread "main" java.util.concurrent.TimeoutException
at testexception.Test.test(Test.java:12)
at testexception.Test.main(Test.java:8)

从上面可以看出,编译时异常必须在函数中声明,调用者也必须在函数中处理.



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值