我很想知道使用throw new Exception()
和new Exception()
的最佳实践。在使用new Exception()
的情况下,我看到代码移动到下一个语句,而不是抛出异常。
但是我被告知我们应该用new Exception()
来扔RuntimeException
。
有人能解释一下吗?
new Exception()
表示创建一个实例(与创建新的Integer(…)相同)但是在抛出它之前不会发生异常…
考虑下面的代码片段:
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()将抛出一个异常,如果参数是负的,但是如果参数为负
Exception e = new Exception ();
只是创建一个新的异常,稍后可以抛出。使用
throw e;
与
throw new Exception()
在一行
创建并抛出异常创建并抛出运行时异常
throw new RuntimeException()
new Exception()
意味着您正在创建一个Exception类型的新实例。这意味着您只是实例化了一个类似于new String("abc")
的对象。在接下来的几行代码执行中,当您准备抛出Exception
类型的异常时,您可以这样做。
当你说throw new Exception()
时,这意味着你在说将程序控制移动到调用者,并且不执行该throw语句之后的进一步语句。
当你发现没有办法继续执行并因此让调用者知道我无法处理这种情况时,你会这样做,如果你知道如何处理这种情况,请这样做。
没有最好的做法,就像你比较橘子和苹果一样。但请记住,当抛出异常时,您总是抛出一个有意义的异常,就像IO一样,如果文件不存在,它会抛出FileNotFoundException
而不是其父IOException
。