【问题标题】:how to use throws Exception? [closed]如何使用抛出异常? [关闭]
【发布时间】:2022-01-18 07:22:58
【问题描述】:

这是我的类 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 method(),我怎么能在这个方法中抛出异常?

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

这是我的主类(),我需要在我的主类中抛出任何异常吗?:

        
        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());
        }

【问题讨论】:

  • 不清楚你在问什么。请详细说明。
  • @tgdavies 我使用 checkinputSalary() 方法检查字符串薪水是否不是双倍,小于 0,它将打印“错误”并循环直到用户输入正确,然后我调用它在 inputPersonInfo(String String Double) 中进行检查,但现在我的老师要求我使用 inputPersonInfo(String String Double) throws Exception{} 所以我不能再使用外部方法了

标签: java exception


【解决方案1】:

throws Exception 用于定义一个方法来表示该方法可能会抛出错误,以防万一出现问题。它只是一个信号,它不处理任何事情。

如果您将此添加到方法声明中,无论您在何处调用此方法,都将要求您(IDE、编译器..)添加处理机制,例如 try-catch 子句,或添加另一个 @ 987654322@ 到调用“危险”方法的方法的声明。

例子:

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()
}

【讨论】:

    【解决方案2】:

    对于未经检查的异常:

    NumberFormatException是一个RuntimeException,这是一个“未经检查的异常”,这意味着即使你不try...catch它,它最终也会被抛出到外部(调用者)。

    在外部(调用者),如果你愿意,你可以try...catch它,或者你可以忽略它。如果发生异常,它将被抛出。如果你的程序是控制台程序,它会被抛出并显示在控制台窗口中。

    这也意味着您的main 方法不必显式地try..catchthrows 它,编译器仍然会成功编译它。

    对于已检查的异常:

    另一方面,关于“检查异常”,您必须try..catch 否则编译器会显示错误。如果不想try...catch当前方法中的异常,可以在方法签名中使用throws Exception。例如IOException:

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

    在调用上述inputPersonInfo()main 方法中,您必须在主方法签名中使用try..catchthrows

    例如:带有 IOException(已检查的异常)

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

    【讨论】:

    • tôiNóiTiếngviệt ^hiểuhơn,vậtnếukhôngdùngcái尝试...
    • Lặp lại nhiều lần được nhé。 trừKhinóbị @987654338 @,cònKhôngCứ @987654339 @liêntụcrangoài,ngaycảthằng @987654340 @cũng @cũng @cũng @9876541 @ra rain/spant rain/sply/spant r hiy hir/shi r hiyệ
    • 我上面的评论英文(对不起,我不能在 5 分钟后编辑它):是的,我们可以从一个方法到另一个方法抛出异常,直到我们想try...catch 它,甚至我们不想抓住它,我们也可以把它扔到main方法之外。
    【解决方案3】:

    创建方法,这样一开始就不会抛出异常:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 2012-01-21
      • 2014-01-17
      • 2011-12-10
      相关资源
      最近更新 更多