對於我來說,這些代碼使用關鍵字拋出來聲明運行時異常
static int faktorial (int n) throws ArithmeticException {
if ((n < 0) || (n > 31)) {
throw new ArithmeticException();
}
if (n > 1) {
return n * faktorial(n - 1);
}
else {
return 1;
}
}
和相同的代碼投擲無
throws ArithmeticException
做同樣的,當我用下面的代碼使用它:
public static void main(String[] args) {
try {
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Insert integer number: ");
n = sc.nextInt();
System.out.println(n + "! = " + faktorial(n));
}
catch (InputMismatchException e) {
System.out.println("Not an integer number!");
e. printStackTrace();
}
catch (RuntimeException e) {
System.out.println("Number is too big!");
e. printStackTrace();
}
}
可能有人形容我,如果使用的
throws ArithmeticException
在我的代碼中有一些優點。
我也會喜歡使用關鍵字throws
的一個很好的例子。非常感謝你!
它有它的上升空間,所以你不能只說這是多餘的 – dantuch
非常感謝您! – mcihak
@Keppil它不會**逼你抓住它。 – dantuch