12

我试图弄清楚为什么我必须throw在 main 方法中出现异常,而我有try/catch块可以处理这些异常?即使我删除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();
        } 
4

6 回答 6

10

如果您希望它由“更高”函数处理,则仅抛出异常。

注意:异常不只是在抛出时消失。它仍然需要处理。

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

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

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

如果您已经在使用try/catch块来捕获异常,那么您无需再抛出该异常。

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);
  }
}
于 2013-07-13T10:33:46.990 回答
3

Any method has two choices to deal with the exceptions that can occur in that method:

First choice is to handle the exception within the method using a catch and don't tell anyone about it. This approach is useful in handling errors, which will have no effect on the method calling this.

Second choice is to catch the exception in the method, may or may not do something to handle the exception. Additionally tell the calling method that something has gone wrong, so you do the needful. This approach is useful and should be used for exceptions which are causing a problem that need to be propagated above to the calling hierarchy.

I don't think it is really a good idea to throw exceptions form the main method. Because even if you don't throw it, JVM will get the exception and will exit. The best you can do is to try to catch those excepitons and do some corrective action within the main. If the exception is catastrophic no matter whether you throw it or not, the program will exit.

于 2013-07-13T10:44:41.350 回答
2

简单的回答:

如果所有检查的异常都由代码处理,则无需声明要抛出的方法。

也可以看看:

http://www.javapractices.com/topic/TopicAction.do?Id=129

于 2013-07-13T10:33:33.257 回答
1

有时调用方不希望抛出异常,因为他们不想处理此类异常。在这种情况下,我们确实将可能引发异常的代码包含在 try catch finally 块中。

但是在您想专门捕获某个异常并尝试对其进行处理的情况下,或者如果您想向调用方抛出一个客户异常,那么您应该首先捕获它。

建议永远不要吞下异常,也不要捕获并重新抛出相同的异常。

于 2013-07-13T10:33:59.580 回答
0

基本上检查的异常需要处理。编译器强制这样做。您可以通过 try catch 或 throws 子句来做到这一点。其中之一就足够了。

当您不想通过调用代码来处理该异常时,您将采用第一种方法。

于 2013-07-13T10:40:16.743 回答
0

您正在使用 try-catch 处理代码中的异常。这就是原因。

于 2013-10-24T21:25:12.563 回答