我想弄清楚为什么我必须在 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/