【发布时间】:2015-08-16 08:34:25
【问题描述】:
在java中的异常处理方面,我已经看到所有try-catch块都需要一种它必须处理的异常,更常见的是:
catch(Exception e){
System.out.println("Error occured");
}
现在我的问题是为什么它需要Exception e,因为它没有在任何地方使用?
关于我刚刚编写的以下代码的第二个问题:
Scanner scanner = new Scanner(System.in);
int x = 1;
do {
try {
System.out.println(" Enter your first number:");
int n1 = scanner.nextInt();
System.out.println(" Enter your second number:");
int n2 = scanner.nextInt();
int result = n1 / n2;
System.out.println("");
System.out.println("The result is : " + result);
x = 2;
} catch (ArithmeticException arithmeticException) {
System.out.println("Error occured");
}
} while (x == 1);
}
在上面的代码中,我看到该程序可以使用catch (ArithmeticException arithmeticException) 和catch(Exception e) 两个参数。 那么这两种不同类型的错误如何处理同一个代码块呢?
【问题讨论】:
-
异常是对象,而您的“自定义”异常只是该通用异常的后代。 ALL 异常可以被通用
catch (Exception e)捕获,但您也可以有多个捕获块,每个捕获块中的一个。例如catch (FailedAssertion e),catch(FileNotFound e),等等等等。 -
你不需要捕捉
Exception,你可以捕捉Throwable,它是Exception和Error的超类。但是,应该注意的是,大多数Errors 并不是真的要被抓住(例如OutOfMemoryError);您可能想在它们发生时尝试进行某种清理,但通常会重新抛出原始的Throwable。
标签: java exception error-handling exception-handling runtime-error