How to throw RuntimeException (“cannot find symbol”)

后端 未结 9 1072
别跟我提以往
别跟我提以往 2021-02-03 18:47

I\'m trying to throw an exception in my code like this:

throw RuntimeException(msg);

But when I build in NetBeans I get this error:

<         


        
相关标签:
9条回答
  • 2021-02-03 19:30
    throw new RuntimeException(msg);
    

    unlike any other Exceptions I think RuntimeException is the only one that will not stall the program but it can still keep running and recover just print out a bunch of Exception lines? correct me if I am wrong.

    0 讨论(0)
  • 2021-02-03 19:33

    An Exception is an Object like any other in Java. You need to use the new keyword to create a new Exception before you can throw it.

    throw new RuntimeException();
    

    Optionally you could also do the following:

    RuntimeException e = new RuntimeException();
    throw e;
    

    Both code snippets are equivalent.

    Link to the tutorials for completeness.

    0 讨论(0)
  • 2021-02-03 19:35

    You need to create the instance of the RuntimeException, using new the same way you would to create an instance of most other classes:

    throw new RuntimeException(msg);
    
    0 讨论(0)
提交回复
热议问题