以下实例演示了重载方法的异常处理:
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示例代码展示了方法重载的概念及如何进行异常处理。具体包括不同类型的参数传递给相同名称的方法时如何区分调用,并且演示了在方法中抛出和捕获异常的具体实现。
3865

被折叠的 条评论
为什么被折叠?



