[英]How to catch the Arithmetic Exception
我試圖通過使用try catch塊或拋出異常方法來捕獲以下代碼中的異常。我已經嘗試過使用try catch塊並在代碼中的不同位置拋出異常方法,但是我仍然無法捕獲異常
package thowsexception;
import java.io.IOException;
import java.rmi.AccessException;
public class IOexception {
public int example1(int i, int j) throws ArithmeticException {
int k ;
if (i == 0){
throw new ArithmeticException("cannot Divide By 0");
}
return i /j ;
// try {
//
// k = i/j ;
// }
//
// catch (ArithmeticException e){
//
// System.out.println("Error: Don't divide a number by zero");
// }
}
}
主班
package thowsexception;
import java.io.IOException;
public class IOexception {
public static void main(String[] args) throws ArithmeticException {
example e = new example();
e.example1(5,0);
}
}
您可以用兩種不同的方式解決此問題
public int example1(int i, int j) throws ArithmeticException {
if (j == 0) {// you should check j instead of i
throw new ArithmeticException("cannot Divide By 0");
}
return i / j;
}
要么
public int example1(int i, int j) throws ArithmeticException {
try {
return i / j;
}
catch (ArithmeticException e) {
throw new ArithmeticException("Error: Don't divide a number by zero");
}
}
但是第一個比第二個是正確的,因為未檢查的異常代表編程錯誤,並且應該修復編程錯誤,並且大多數情況下,由於用戶在用戶程序交互過程中提供的錯誤數據而導致發生這些異常,因此我們應該防止這些類型的錯誤而不是捕獲它。
閱讀更多關於更好地了解未檢查的異常與如何檢查異常的更好方法
您當前的代碼指出:
if (i == 0) {
throw new ArithmeticException("cannot Divide By 0");
}
return i/j ;
這樣做的問題是,您正在檢查分數i的分子是否等於0。如果分子為0,則分數是可以的,因為您沒有被0除。您需要檢查j = = 0,因為您要除以j。
if (j == 0) {
throw new ArithmeticException("cannot Divide By 0");
}
return i/j ;
是正確的代碼。
您可以采取什么措施來捕獲異常
主班
package thowsexception;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
IOexception e = new IOexception();
try { e.example1(5,0);
}
catch (ArithmeticException e1){
}
}
}
IOexception類
package thowsexception;
import java.io.IOException;
import java.rmi.AccessException;
public class IOexception {
public void example1(int i, int j) {
int k = i/j;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.