编译时异常与运行时异常区别

来源:互联网 发布:产品分析软件 编辑:程序博客网 时间:2024/06/18 08:24

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

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


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

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

ArithmeticException运行时异常
[java] view plain copy
  1. public class Test {  
  2.     public static  int a=0;  
  3.     public static void main(String[] args){  
  4.         // TODO Auto-generated method stub  
  5.           a = test(4,0);  
  6.     }  
  7.     public static int test(int a,int b){  
  8.         if(b==0){  
  9.           throw new ArithmeticException();  
  10.         }  
  11.         return a/b;  
  12.     }  
  13. }  
打印结果:
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秒,抛出连接超时异常。
[java] view plain copy
  1. package testexception;  
  2.   
  3. import java.util.concurrent.TimeoutException;  
  4.   
  5. public class Test {  
  6.     public static void main(String[] args)throws TimeoutException{  
  7.         // TODO Auto-generated method stub  
  8.          test(11);  
  9.     }  
  10.     public static void test(int i) throws TimeoutException{  
  11.         if(i>10)  
  12.           throw new TimeoutException();  
  13.         System.out.println("连接没有超时");  
  14.     }  
  15. }  

打印结果:

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

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