代码之家  ›  专栏  ›  技术社区  ›  Greg

如何抛出RuntimeException(“找不到符号”)

  •  31
  • Greg  · 技术社区  · 15 年前

    我试图在我的代码中抛出如下异常:

    throw RuntimeException(msg);
    

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

    我需要进口什么东西吗?我拼写错了吗?我肯定我在做什么蠢事:-(

    8 回复  |  直到 12 年前
        1
  •  125
  •   slm Vikas Hardia    7 年前

    throw new RuntimeException(msg);

    你需要 new

        2
  •  36
  •   Michal    12 年前

    Exception 是一个 Object new 关键字来创建新的 在你能之前 throw 是的。

    throw new RuntimeException();
    

    RuntimeException e = new RuntimeException();
    throw e;
    

    这两个代码段是等价的。

    Link to the tutorials for completeness.

        3
  •  15
  •   Dean J    15 年前

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

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

    回想起来,我错过了添加原因 为什么? 使用Exception而不是RuntimeException@杰伊,在下面的评论中,加入了有用的一点。RuntimeException不是选中的异常;

    • 方法签名不必声明可能引发RuntimeException。
        4
  •  6
  •   Sudhakar    15 年前

    您必须在抛出它之前实例化它

    throw new RuntimeException(arg0) 
    

    附言:

        5
  •  4
  •   naikus    15 年前
    throw new RuntimeException(msg); // notice the "new" keyword
    
        6
  •  3
  •   RHSeeger    15 年前

    您需要使用 new

    throw new RuntimeException(msg);
    
        7
  •  1
  •   dillip    11 年前

        8
  •  1
  •   SSpoke    10 年前
    throw new RuntimeException(msg);
    

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

        9
  •  0
  •   Keshav Gera    7 年前

    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 
    

    使用新关键字清除内存[因为使用并抛出]

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
    
            //do your work here..
        }
    }, 1000);