publicclassMain{doublemethod(int i)throwsException{return i/0;}booleanmethod(boolean b){return!b;}staticdoublemethod(int x,double y)throwsException{return x + y ;}staticdoublemethod(double x,double y){return x + y -3;}publicstaticvoidmain(String[] args){Main mn =newMain();try{System.out.println(method(10,20.0));System.out.println(method(10.0,20));System.out.println(method(10.0,20.0));System.out.println(mn.method(10));}catch(Exception ex){System.out.println("exception occoure: "+ ex);}}}
结果
上面的代码示例将产生以下结果。
30.027.027.0
exception occoure: java.lang.ArithmeticException:/ by zero
下面是另一个例子,用Java中的重载方法处理异常
classNewClass1{voidmsg()throwsException{System.out.println("this is parent");}}publicclassNewClassextendsNewClass1{NewClass(){}voidmsg()throwsArithmeticException{System.out.println("This is child");}publicstaticvoidmain(String args[]){NewClass1 n =newNewClass();try{
n.msg();}catch(Exception e){}}}