- 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
廣告