Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw RuntimeException ("cannot find symbol")

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:

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

Do I need to import something? Am I misspelling it? I'm sure I must be doing something dumb :-(

like image 906
Greg Avatar asked Aug 04 '10 13:08

Greg


People also ask

Can you throw runtime exception?

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

How do you throw an exception in Java?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.

How do you resolve define and throw a dedicated exception instead of using a generic one?

Go to Solution. You should not throw generic exceptions. You should be subclassing Exception and then throwing your subclass, so that the type of the exception actually provides information about what is going on, allowing clients of the function to catch and treat it appropriately.


2 Answers

throw new RuntimeException(msg);

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

like image 70
j flemm Avatar answered Sep 19 '22 21:09

j flemm


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.

like image 26
jjnguy Avatar answered Sep 19 '22 21:09

jjnguy