43

我试图在我的代码中抛出一个异常,如下所示:

throw RuntimeException(msg);

但是当我在 NetBeans 中构建时,我得到了这个错误:

C:\....java:50: cannot find symbol
symbol  : method RuntimeException(java.lang.String)
location: class ...
        throw RuntimeException(msg);
1 error

我需要导入一些东西吗?我拼错了吗?我确定我一定在做一些愚蠢的事情:-(

4

9 回答 9

129

throw new RuntimeException(msg);

你需要new在里面。它是创建一个实例并抛出它,而不是调用一个方法。

于 2010-08-04T13:57:24.300 回答
38

An与 JavaException中的Object任何其他代码一样。您需要先使用new关键字创建一个新关键字。Exceptionthrow

throw new RuntimeException();

您还可以选择执行以下操作:

RuntimeException e = new RuntimeException();
throw e;

两个代码片段是等效的。

链接到教程以确保完整性。

于 2010-08-04T13:57:37.090 回答
15

正如其他人所说,在抛出之前实例化对象。

只想加一点;抛出 RuntimeException 是非常罕见的。API 中的代码抛出 this 的子类是正常的,但通常,应用程序代码会抛出异常,或者扩展异常但不扩展 RuntimeException 的东西。

回想起来,我错过了添加使用 Exception 而不是 RuntimeException的原因;@Jay,在下面的评论中,添加了有用的部分。RuntimeException 不是检查异常;

  • 方法签名不必声明可能会引发 RuntimeException。
  • 该方法的调用者不需要捕获异常,或以任何方式确认它。
  • 以后尝试使用你的代码的开发者,除非仔细观察,否则不会预料到这个问题,而且会增加代码的维护负担。
于 2010-08-04T14:45:34.750 回答
6

你必须在扔之前实例化它

throw new RuntimeException(arg0) 

PS:有趣的是,Netbeans IDE 应该已经指出编译时错误

于 2010-08-04T14:00:29.347 回答
4
throw new RuntimeException(msg); // notice the "new" keyword
于 2010-08-04T13:57:26.877 回答
3

您需要创建 RuntimeException 的实例,使用new与创建大多数其他类的实例相同的方式:

throw new RuntimeException(msg);
于 2010-08-04T13:57:41.837 回答
1

仅针对其他人:确保它是新的 RuntimeException,而不是需要错误作为参数的新 RuntimeErrorException。

于 2014-07-18T18:05:19.103 回答
1
throw new RuntimeException(msg);

与任何其他异常不同,我认为 RuntimeException 是唯一不会停止程序但它仍然可以继续运行和恢复的异常,只是打印出一堆异常行?如果我错了,请纠正我。

于 2016-03-24T13:12:47.400 回答
0

使用 new 关键字,我们总是创建一个实例(新对象)并抛出它,而不是称为方法

throw new RuntimeException("Your Message");

You need the new in there. It's creating an instance and throwing it, not calling a method.

int no= new Scanner().nextInt();   // we crate an instance using new keyword and throwing it 

使用新关键字 memory clean [因为 use 和 throw]

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..
    }
}, 1000);
于 2019-06-10T09:33:33.123 回答