Java 异常处理编译错误:异常;必须被抓住或宣布被抛出
我不知道为什么我会犯这样的错误,我觉得我错过了一些明显的东西。它发生在以下行:Verify.validateEnumber;错误:Program5.java:23:error:unreportedexception;必须被抓住或宣布被抛出。如有任何建议,将不胜感激 -克里斯Java 异常处理编译错误:异常;必须被抓住或宣布被抛出,java,Java,我不知道为什么我会犯这样的错误,我觉得我错过了一些明显的东西。它发生在以下行:Verify.validateEnumber;错误:Program5.java:23:error:unreportedexception;必须被抓住或宣布被抛出。如有任何建议,将不胜感激 -克里斯 import java.util.Scanner; public class Program5 { public static void main(String[] args) { //
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());
}
}
}
让我们尝试使用更通用的捕获: 试一试{ .... }卡奇{ }
通过这种方式,您捕获了所有错误,因为每个错误都扩展了类错误。根据您的代码,validateint方法可能引发3种类型的异常: 1号异常 2数字下限例外 3 NumberNegativeException 因此,validateint方法的代码可能如下所示:
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");
}
生成的错误为:
error: unreported exception Exception; must be caught or declared to be thrown
这表示抛出的异常的类型高于catch块指定的类型
因此,在validate方法中的某个地方,您正在抛出一个类型为exception的异常。只要纠正它,你就会没事的 解决方案出现在错误消息Yes中,catchException或let The main方法抛出exception这必须是一个重复大约1000次。错误:未报告的异常;必须被捕获或声明为抛出意味着在该方法中的某个地方可能会抛出类异常的异常,很可能来自Validate方法。必须为Exception提供catch语句,或者向方法头添加throws Exception子句。如果您查看验证的源代码,可能有一个抛出异常子句。
error: unreported exception Exception; must be caught or declared to be thrown