异常处理编译错误:异常;必须被抓住或宣布被抛出

时间:2014-10-17 16:48:48

标签: java

我不知道为什么我会收到这个错误并且有一种感觉我在这里遗漏了一些明显的东西。它出现在该行上:Verify.Validate(number);错误:Program5.java:23:错误:未报告异常异常;必须被抓住或宣布被抛出。任何建议将不胜感激。

-Chris

import java.util.Scanner;

public class Program5 
{

    public static void main(String[] args) 
    {
      // The driver class should instantiate a Verify object with a range of 10 to 100.
      Verify Verify = new Verify(10, 100);

      //Prompt the user to input a number within the specified range.
      System.out.print("Input a number between 10-100: ");

      // Use a Scanner to read the user input as an int.
      Scanner input = new Scanner(System.in); 
      int number = input.nextInt();

      // Use Try/Catch to test number
      try 
      {
            Verify.Validate(number);
            System.out.println("Number entered: " + number);
      } 
      catch (NumberNegativeException ex) 
      {
            System.out.println(ex.getMessage());
      } 
      catch (NumberLowException ex) 
      {
            System.out.println(ex.getMessage());
      } 
      catch (NumberHighException ex) 
      {
            System.out.println(ex.getMessage());
      } 
    }    
}

2 个答案:

答案 0 :(得分:1)

根据您的代码,您的validate(int)方法可能会抛出3种类型的异常:

1)NumberHighException

2)NumberLowException

3)NumberNegativeException

因此 validate(int)方法的代码可能如下所示:

public void validate(int number) throws NumberHighException, NumberLowException,
                                  NumberNegativeException {
   if(number > 100)
       throw new NumberHighException("Number is High");
   if(number < 10)
       throw new NumberLowException("Number is Low");
   if(number < 0)
       throw new NumberNegativeException("Number is Negative");
   else
       System.out.println("Your Entered Number is valid");
}

现在,在编译代码时,您将获得错误

catch (NumberNegativeException ex)  // Line no 23, where you are getting the error
{
    System.out.println(ex.getMessage());
}

产生的错误是:

 error: unreported exception Exception; must be caught or declared to be thrown

这表明抛出的异常比catch块指定的更高(超类)类型。

因此,在 validate()方法的某处,您将抛出异常类型的异常。纠正它,你会没事的。

答案 1 :(得分:-1)

让我们尝试使用更常见的捕获: 尝试{ .... } catch(例外e){ } 通过这种方式,您捕获了所有错误,因为每个错误都会扩展类Error