[英]Exceptions in Java - Try/ Catch
我正在學習 Java,我有這個程序可以根據用戶編寫的日期和月份來告訴符號。 該程序按原樣運行,但如果用戶輸入 90 天左右,該程序不會評估該“錯誤”。 我可以通過 try/catch 來糾正這個問題嗎? 如果是這樣,我該怎么寫? 這是代碼(一部分),提前致謝
import java.util.Scanner;
public class Signo{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int day, month;
System.out.println("Day Input:");
day=in.nextInt();
System.out.println("Month Input:");
month=in.nextInt();
int result=getSign(day,month);
}
private static int getSign(int day, int month){
switch(month){
case 1:
if(month==1 && day>=20){
System.out.println("Your sign is Aquarius");
}else{
System.out.println("Your sign is Capricorn");
}
break;
//etc
}
return day;
}
}
實際上沒有錯誤。 你要求一個整數,而用戶提供的正是這個。 由您來驗證它是否是您當前邏輯的有效數字。 我也會重寫你的 getSign() 方法,混合開關和 if 真的沒有意義。 至少在你的情況下是這樣。
我會做這樣的事情:
day=in.nextInt();
if(day > 30) {
while(day > 30) {
// Number is too high, feel free to spit this message out
day=in.nextInt();
}
或者甚至更好:
while(day > 30) {
day=in.nextInt();
}
你也可以提取你的day = in.nextInt();
到單個方法,如果有效/無效則返回一個布爾值
很簡單,真的...
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
這就是你真正需要的。 只需將您認為可能會中斷的代碼放在適當的位置即可。
不過,在閱讀了評論后,我同意這對您正在做的事情來說太過分了。
您只需要為 While 循環設置條件:
boolean goodAnswer = false;
while goodAnswer == false{
System.out.println("Day Input:");
day=in.nextInt();
if (day<31) { goodAnswer=true; }
}
像這樣的例程將有效地繼續要求一個整數,直到它得到它喜歡的一個。 只有這樣它才會離開循環。 對於這類事情,這是一種相當常見的方法。
你會尋找斷言/驗證的東西,這通常是在方法的參數上完成的:
public void doSomething(int num) {
if (num > 30) {
throw new IllegalArgumentException("num is too high!");
}
//continue knowing that num is <= 30
}
有一些 API(如 Apache Commons)將其簡化為一行:
Validate.isTrue(num <= 30, "num is too high!");
本質上與上面的代碼相同,但要短得多。
所有這些都是數據驗證的一部分
對此進行邏輯循環:
boolean valid = false;
while (!valid) {
try {
//take input, pass to #doSomething
valid = true;
} catch (IllegalArgumentException ex) {
//repeat / error out
}
}
//continue
盡管您可能希望使用 isValid 檢查之類的東西手動驗證自己:
private boolean isValidDay(int num) {
return num > 0 && num < 31;
}
//In method
Validate.isTrue(isValidDay(num), "num is not valid!");
//Without try/catch
if (isValidDay(num)) {
//call #doSomething etc
}
您根本不應該使用 try/catch。
Java 中有兩種類型的異常 - 捕獲/檢查異常和未捕獲/未檢查異常(RuntimeException、Error 及其子類)。 您的情況中的異常是未捕獲/未檢查異常的一個示例,因為在運行時由於用戶輸入而發生這種情況。
大多數情況下,您不需要 try/catch 塊來處理這些異常。 事實上,您甚至不需要處理這些異常。 所以你會怎么做?
您改進代碼中的邏輯,以便確實發生異常。 例如,您可以使用 while 循環不斷向用戶詢問有效數字。
if(day > 30) {
While(day > 30) {
//send message to the user
day = in.nextInt();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.