“引发新异常”之间的区别在于:和“新异常”? [英] Difference between "throw new Exception" and "new Exception"?
问题描述
我想知道使用抛出新的Exception()
和 new Exception()
的最佳实践。如果使用 new Exception()
,我已经看到代码移至下一条语句,而不是抛出异常。
I am interested to know best practice to use throw new Exception()
and new Exception()
. In case of using new Exception()
, I have seen that code moves to next statement instead of throwing exception.
但是我被告知应该使用 new Exception()
引发 RuntimeException
。
But I am told that we should use new Exception()
to throw RuntimeException
.
任何人都可以对此发表看法吗?
Can anyone throw some light on this ?
推荐答案
new Exception()
表示创建一个实例(与创建新的Integer(...)相同)
,但是除非抛出它...
new Exception()
means create an instance (same as creating new Integer(...))
but no exception will happen until you throw it...
请考虑以下代码段:
public static void main(String[] args) throws Exception {
foo(1);
foo2(1);
}
private static void foo2(final int number) throws Exception {
Exception ex;
if (number < 0) {
ex = new Exception("No negative number please!");
// throw ex; //nothing happens until you throw it
}
}
private static void foo(final int number) throws Exception {
if (number < 0) {
throw new Exception("No negative number please!");
}
}
方法foo()将抛出如果参数为负但
则为异常,如果参数为负,则foo2()方法将创建异常的实例
the method foo() will THROW an exception if the parameter is negative but the method foo2() will create an instance of exception if the parameter is negative
这篇关于“引发新异常”之间的区别在于:和“新异常”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!