如何使用 Java 中的重载方法处理异常
问题描述
如何使用重载方法处理异常?
解决方案
此示例显示如何使用重载方法处理异常。您需要在每个方法或使用方法的地方都有一个 try catch 块。
public class Main {
double method(int i) throws Exception {
return i/0;
}
boolean method(boolean b) {
return !b;
}
static double method(int x, double y) throws Exception {
return x + y ;
}
static double method(double x, double y) {
return x + y - 3;
}
public static void main(String[] args) {
Main mn = new Main();
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.0 27.0 27.0 exception occoure: java.lang.ArithmeticException: / by zero
以下是另一个使用 Java 中重载方法处理异常的示例
class NewClass1 {
void msg()throws Exception{System.out.println("this is parent");}
}
public class NewClass extends NewClass1 {
NewClass() {
}
void msg()throws ArithmeticException{System.out.println("This is child");}
public static void main(String args[]) {
NewClass1 n = new NewClass();
try {
n.msg();
} catch(Exception e){}
}
}
上述代码示例将产生以下结果。
This is child
java_exceptions.html

