【问题标题】:Difference between "throw new Exception" and "new Exception"?“抛出新异常”和“新异常”之间的区别?
【发布时间】:2016-10-23 07:38:27
【问题描述】:

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

但有人告诉我,我们应该使用new Exception() 来抛出RuntimeException

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

【问题讨论】:

  • new Exception 意味着创建一个实例(与 new Integer(...) 相同)但在你抛出它之前不会发生异常......
  • “我被告知我们应该使用 new Exception() 来抛出 RuntimeException”由谁?在哪里?凭什么推理? new Exception() 不会抛出实例化的异常。

标签: java exception throw


【解决方案1】:

new Exception() 表示创建实例(与创建 new Integer(...) 相同) 但在你抛出它之前不会发生异常......

考虑以下sn-p:

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() 将创建一个异常实例

【讨论】:

    【解决方案2】:
    Exception e = new Exception ();
    

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

    throw e;
    

    throw new Exception()
    

    在一行中创建并抛出异常

    创建并抛出运行时异常

    throw new RuntimeException()
    

    【讨论】:

      【解决方案3】:

      new Exception() 表示您正在创建一个 Exception 类型的新实例。这意味着您只是在实例化一个类似于 new String("abc") 等其他对象的对象。当您即将在接下来的几行代码执行中抛出 Exception 类型的异常时,您会这样做。

      当您说throw new Exception() 时,这意味着您是在说将程序控制权移至调用者,并且不要在该 throw 语句之后执行进一步的语句。

      您会在您发现无法继续执行并进一步执行的情况下执行此操作,因此让调用者知道我无法处理这种情况,如果您知道如何处理这种情况,请这样做.

      没有最佳做法,例如将橙子与苹果进行比较。但是请记住,在抛出异常时,您总是会抛出一个有意义的异常,例如 IO 有,如果文件不存在,它会抛出 FileNotFoundException 而不是其父 IOException

      【讨论】:

        猜你喜欢
        • 2011-03-01
        • 2012-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-23
        • 1970-01-01
        相关资源
        最近更新 更多