java - 主方法抛出异常

标签 java exception

我想弄清楚为什么我必须在 main 方法中 throw 异常,而我有 try/catch block 可以处理那些异常(exception)呢? 即使我删除了 throws IllegalArgumentException,InputMismatchException 部分,该程序仍然可以编译并完美运行。

public static void main(String[] args) throws IllegalArgumentException,InputMismatchException{
    boolean flag = true;
    Scanner in = new Scanner(System.in);
    do{
        try{
            System.out.println("Please enter the number:");
            int n = in.nextInt();
            int sum = range(n);
            System.out.println("sum = " + sum);
            flag = false;
        }
        catch(IllegalArgumentException e){
            System.out.println(e.getMessage());
        }
        catch(InputMismatchException e){
            System.out.println("The number has to be as integer...");
            in.nextLine();
        } 

最佳答案

只有在希望由“更高”函数处理时才抛出异常。

(注意:异常不是抛出就消失,还是要处理。)

public void functionA() throws Exception{
  throw new Exception("This exception is going to be handled elsewhere");
}

当您想立即处理异常时,您可以使用 try/catch block 。

public void functionB(){
  try{
    throw new Exception("This exception is handled here.");
  }catch(Exception e){
    System.err.println("Exception caught: "+e);
  }
}

如果您已经在使用 try/catch block 来捕获异常,那么您就没有必要再抛出该异常了。

public void functionC() throws Exception{
  try{
    throw new Exception("This exception doesn't know where to go.");
  }catch(Exception e){
    System.err.println("Exception caught: "+e);
  }
}

关于java - 主方法抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17629321/

相关文章:

java - 启用/禁用另一个类的表单按钮

java - 设计 GUI 的重要提示?

java - Spring Executorservice 错误处理

java - 为@Nonnull 注释参数编写单元测试

java - 读取每个单词和后面的两个单词并检查java中的一些条件

java - 如何使用 ROME 进行 RSS

c++ - 我应该只对无效输入使用异常处理吗?

java - 在 Spring Integration 中将 MessageHeader 的键设置为 'NEW' 时出现 SpelParseException

java - NoSuchMethodError 在 org.json 中使用 JSONArray

Java加载二进制文件