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)

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



你可能感兴趣的:(Java)