JAVA程序违反了JAVA的语义规则时,JAVA虚拟机就会将发生的错误表示为一个异常。违反语义规则包括2种情况。一种是JAVA类库内置的语义检查。例如数组下标越界,会引发IndexOutOfBoundsException;访问null的对象时会引发 NullPointerException。另一种情况就是JAVA允许程序员扩展这种语义检查,程序员可以创建自己的异常,并自由选择在何时用 throw关键字引发异常。所有的异常都是java.lang.Thowable的子类。
eg:第一种
class Test{
public int devide(int x ,int y) throws Exception{ //
int result = x/y;
return result;
}
}
class TestException{
public static void main(String[] args){
try{
new Test().devide(3,0);
}catch(Exception e){
System.out.println(e.getMessage());//虽然Exception除了Constructor之外没有其它的函数,
//但它继承了Throwable类.
}
System.out.println("Program running here");
}
}
当编写Test class不知道它是否抛出异常时,可以在devide methods方法后添加 throws Exception 就可以..而在TestException中必须处理抛出的异常.
eg:第二种
如果自己定义异常类,必须继承Exception,也就是它的子类.
class Test{
public int devide(int x ,int y) throws Exception{ //
if(y < 0)
throw DevideMyMinusException("devide is" + y);
int result = x/y;
return result;
}
}
class DevideMyMinusException extends Exception{
public DevideMyMinusException (String msg){
super(msg); //调用父类(Exception)的Construtor,主函数getMessage()输出自定义的异常:"devide is..."
}
}
eg.第三种
可以抛出多个异常类.
class Test{
public int devide(int x ,int y) throws ArithmeticException,DevideMyMinusException{ //
if(y < 0)
throw new DevideMyMinusException("devide is" + y);
int result = x/y;
return result;
}
}
class DevideMyMinusException extends Exception{
public DevideMyMinusException (String msg){
super(msg);
}
}
class TestException{
public static void main(String[] args){
try{
new Test().devide(3,-1);
}catch(ArithmeticException e){
System.out.println("program running into ArithmeticException ");
e.printStackTrace();
}catch(DevideMyMinusException e){
System.out.println("program running into DevideMyMinusException");
e.printStackTrace();
}catch(Exception e){
System.out.println(e.getMessage)
)finally{
System.out.println("finally running");//不管程序发生异常没有,finally代码块都要执行.
}
System.out.println("Program running here");
}
}
1.程序根据异常类型的匹配.自动进入相应的catch语句.Exception应放在其它异常语句后,因为他们都继承Exception ,其它异常要放在后面,就没有什么意义了.
2.try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后? 会执行,而且在return 前执行.
3.什么时候finally里的代码不会执行呢? 当出现System.exit(0);时,它不会执行,程序会退出.