关于异常Exception
1、定义
异常定义了程序中遇到的非致命的错误,而不是编译时的语法错误,如程序要打开一个不存在的文件、网络连接中断、操作数越界、装在一个不存在的类等等。
2、知识总结
①遇到异常时,进入了其中一个catch语句,那么就不会进入它之后的其他catch语句
②无论程序是否发生异常,都会执行finally里的语句,除非出现退出程序(System.exit(0))的语句,finally才不会被执行
③catch(Exception e)异常不能放置于第一个异常,只能把它放在最后,这样才能来捕获它之前的catch语句都不能捕获的异常如果和上面的异常都不匹配,就进入catch(Exception e)异常
④如果父类扔出多个异常,那么重写(覆盖)方法必须扔出那些异常的一个子集,也就是说不能扔出新的异常
3、实例
class Test
{
public int devide(int x,int y) throws Exception
{
if(y<0)
throw new DevideByMinusException("deviser is"+ y);
int result = x/y;
return result;
}
}
class DevideByMinusException extends Exception
{
public DevideByMinusException(String msg)
{
super(msg);
}
}
class TestException
{
public static void main(String args[])
{
try
{
System.out.println(new Test().devide(3,0));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println("finally");
}
System.out.println("program is running here");
}
}