“抛出新异常”和“新异常”之间的区别?

新手上路,请多包涵

我有兴趣了解使用 throw new Exception()new Exception() 的最佳实践。在使用 new Exception() 的情况下,我看到代码移动到下一条语句而不是抛出异常。

但我被告知我们应该使用 new Exception() 来抛出 RuntimeException

任何人都可以对此有所了解吗?

原文由 Vineet Setia 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 420
2 个回答

new Exception() 表示创建一个实例(与创建 new 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() 将抛出异常,但如果参数为负,方法 foo2() 将创建异常实例

原文由 ΦXocę 웃 Пepeúpa ツ 发布,翻译遵循 CC BY-SA 3.0 许可协议

Exception e = new Exception ();

只是创建一个新的异常,您稍后可以抛出它。使用

throw e;

然而

throw new Exception()

在一行中创建并抛出异常

创建并抛出运行时异常

throw new RuntimeException()

原文由 Daniel Scott 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题