- Java 编程示例
- 示例 - 首页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 实用资源
- Java - 快速指南
- Java - 实用资源
如何处理 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.htm
广告