0
如果它是一個正整數值,我想返回傳遞給此方法的值。如果不是,我想拋出異常,這是我在主要方法中捕獲的,然後退出程序。處理正整數的例外
private String posInteger(String input) {
try {
if (Integer.valueOf(input) >= 0) {
return input;
} else {
throw new MyOwnExampleException("Error, number can't be negative.");
}
} catch (NumberFormatException e) {
throw new MyOwnExampleException("Error, number must be an integervalue.");
}
}
我不喜歡,我在try塊的catch塊扔MyOwnExampleException
,然後再次的事實。有沒有更好的方法呢?我一定要拋出我自己的例外。
你爲什麼不喜歡它?他們是兩個完全不同的案例。 –
您可以只拋出NumberFormatException並丟棄try-catch塊。 – deanosaur