异常
class Test
{ public int devide(int x,int y) throws Exception //throws EXception 抛出异常,如果感觉到这个程序可能出现异常,就加上这条语句,在后面的调用中,如果不加try,catch编译就会出错。
{ int result=x/y;
return result;
}
}
class TestException
{ public static void main(String[] args)
{ try
{ new Test().devide(3,0);}
catch(Exception ex)
{ System.out.println(ex.getMessage()); } //getMessage 返回异常的信息,是一个字符串,须要我们自己将这个字符串打印在屏幕上
System.out.println("program is running here!");
}
}
***创建自己的异常***
class Test
{ public int devide(int x,int y) throws Exception
{ if (y<0)
throw new DevideByMinusException("devisor is"+y); //创建一个异常对象,并且抛出这个异常(注意这个用的是throw而不是throws.)
int result=x/y;
return result;
}
}
class DevideByMinusException extends Exception //创建自己的异常(除数为0时产生的异常)
{ public DevideByMinusException (String msg)
{ super(msg); }
}
class TestException
{ public static void main(String[] args)
{ try
{ new Test().devide(3,-1);}
catch(Exception ex) //把上面生成的异常对象传给ex
{ System.out.println(ex.getMessage()); } //输出结果为devisor is -1
System.out.println("program is running here!"); //这个语句,运行时一直都输出
}
}
***抛出多个异常***
class Test
{ public int devide(int x,int y) throws ArithmeticException,DevideByMinusException
{ if (y<0)
throw new DevideByMinusException("devisor is"+y); //创建一个异常对象,并且抛出这个异常(注意这个用的是throw而不是throws.)
int result=x/y;
return result;
}
}
class DevideByMinusException extends Exception //创建自己的异常(除数为0时产生的异常)
{ public DevideByMinusException (String msg)
{ super(msg); }
class TestException
{ public static void main(String[] args)
{ try
{ new Test().devide(3,-1);}
catch(ArithmeticException ex) //算术异常
{ System.out.println("program is running into ArithMetic");
ex.printStackTrace() //printStackTrace将异常情况直接打在我们的屏幕上
}
catch (DevideByMinusException ex) //自定义的除数为负数的异常
{ System.out.println("program is running into ArithMetic");
ex.printStackTrace() //printStackTrace将异常情况直接打在我们的屏幕上
}
catch(Exception ex) //这个异常必须放在所有的,catch的后面
{ System.out.println(ex.getMessage());
System.exit(0); //只有使用了这条语句,才不执行finally语句,这条语句表示程序彻底结束。
}
finally //不管有没有异常发生finally语句都要执行,即使是在程序前面用了return提前返回了,finally也要被执行,不管程序发生什么情况finally语句都要被执行,只有用System.exit(0),程序彻底结束,这条语名才不执行.
{ System.out.println("finally"); }
System.out.println("program is running here!");
}
}
***故意用异常实现程序的跳转***
class Test
{ ....
....
void fun()
{ try
{ if (x==0)
throw new XxxException("xxx");
else
throw new YyyException("yyy");
.....
.....
}
catch (XxxException e) //如果x==0的话,程序跳转到这里
{ ......}
catch (YyyException e) //如果x!=0的话,程序跳转到这里
{.......}
}
.....
}
***子类重写父类的方法,抛出的异常,只能比父类少,不能比父类多***
class Test
{ public int devide(int x,int y) throws ArithmeticException,DevideByMinusException
{ if (y<0)
throw new DevideByMinusException("devisor is"+y);
int result=x/y;
return result;
}
}
class SubTest extends Test
{ public int devide(int x,int y) throws ArithmeticException
//这里抛出的异常只能是父类里有的,如父类方法中的全部抛出的异常,或是其中的异常,或都不写,但一定不能比父类多。
{.....}
}