簡體   English   中英

如何使用拋出異常?

[英]how to use throws Exception?

這是我的 class Person() 方法 inputPersonInfo():

        Scanner sc = new Scanner(System.in);
        System.out.println("Input Information of Person");
        System.out.println("Please input name");
        name = checkInputString();
        System.out.println("Please input address");
        address = checkInputString();
        System.out.println("Please input salary");
        salary = checkInputSalary();        
        return new Person(name,address,salary);
        
        }

這是我對輸入法的檢查:

    public static String checkInputString() {
       //loop until user input true value
        while (true) {
            String s = in.nextLine();
            if (s.isEmpty()) {
                System.err.println("Not empty.");
            } else {
                return s;
            }
        }
    }
    // check if salary is smaller than 0
    public static double checkInputSalary() {
       //loop until user input true value        
        while (true) {
            try {
                double salary = Double.parseDouble(in.nextLine());
                if (salary < 0) {
                    System.err.println("Salary is greater than zero");
                    System.out.print("Please input salary: ");
                } else {
                    return salary;
                }
            } catch (NumberFormatException ex) {
                System.err.println("You must input digidt.");
                System.out.print("Please input salary: ");
            }
        }
    }

如果不使用上面的 checkinput 方法(),我怎么能在這個方法中拋出異常?

public Person inputPersonInfo (String name, String address, Double salary) throws Exception {} 

這是我的主類(),我需要在我的主 class 中拋出任何異常嗎?:

        
        System.out.println("=====Management Person programer=====");        
        
        //call constructor Person
        Person p = new Person(); 
        //enter 3 person 
        for (int i =0; i< 3 ;i++){           
           persons[i] = p.inputPersonInfo(p.getName(), p.getAddress(), p.getSalary());
        }

throws Exception在定義方法時使用,以表明此方法可能會拋出錯誤,以防 go 不正確。 它只是一個信號,它不處理任何事情。

如果您將此添加到方法聲明中,無論您在何處調用此方法,都將需要(由 IDE,編譯器..)添加處理機制,例如 try-catch 子句,或添加另一個throws Exception到聲明調用你的“危險”方法的方法。

例子:

public void dangerousMethod() throws Exception, RuntimeException // Or whatever other exception
{
    throw new Exception("FAKE BUT DANGEROUS");
}
public void anotherMethod()
{
    dangerousMethod(); // <------------ Compiler, IDE will complain that this should be handled in some way
    
    
    // Either add try catch:
    
    try
    {
        dangerousMethod();
    }
    catch(Exception e) // Or whatever specific Exception you have
    {
        // Handle it...
    }
    
    
    // Or add the throws Exception at the head of the anotherMethod()
}

對於未經檢查的異常:

NumberFormatException是一個RuntimeException ,它是一個“未經檢查的異常”,這意味着即使您不try...catch它,它最終也會被拋出到外部(調用者)。

在外部(調用者),您可以try...catch它,或者您可以忽略它。 如果發生異常,它將被拋出。 如果你的程序是控制台程序,它會被拋出並顯示在控制台 window 中。

這也意味着您的main方法不必顯式地try..catchthrows它,編譯器仍然會成功編譯它。

對於檢查的異常:

另一方面,關於“檢查異常”,您必須嘗試try..catch否則編譯器會顯示錯誤。 如果不想try...catch當前方法中的異常,可以在方法簽名中使用throws Exception 例如使用IOException

public Person inputPersonInfo (String name, String address, Double salary) throws IOException {}

在調用上述inputPersonInfo()main方法中,您必須嘗試try..catch或將其throws到主要方法簽名中。

例如:使用 IOException(已檢查的異常)

public static void main(String[] args) throws IOException {
    ...
    inputPersonInfo(...);
    ...
}

創建方法,這樣一開始就不會拋出異常:

public double getSalaryFromUser() {
    String salary = "";
    while (salary.isEmpty()) {
        System.out.print("Please enter a Salary amount: --> ");
        salary = in.nextLine();
        /* Input Validation:
           The RegEx below used as argument for  the String#matches() 
           method checks to see if the supplied string is a unsigned
           Integer or floating point numerical value. If anything other 
           than that is supplied then the error message is displayed. 
           The second condition checks to see if the value is greater 
           than 0.9d             */ 
        if (!salary.matches("\\d+(\\.\\d+)?") || Double.valueOf(salary) < 1.0d) {
            System.out.println("Invalid Entry (" + salary + ")! You must supply a");
            System.out.println("numerical value and it must be greater than zero.");
            System.out.println("Try again...");
            System.out.println();
            salary = "";
        }
    }
    return Double.parseDouble(salary);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM