在main方法中抛出异常

And*_*ski 12 java exception

我试图找出为什么我必须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();
        } 
Run Code Online (Sandbox Code Playgroud)

Eni*_*dan 10

如果希望由"更高"函数处理,则只抛出异常.

(注意:异常不会在抛出时消失.它仍然需要处理.)

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

如果try/catch要立即处理异常,请使用块.

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

如果您已经使用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);
  }
}
Run Code Online (Sandbox Code Playgroud)