How to throw RuntimeException ("cannot find symbol")
throw new RuntimeException(msg);
You need the new
in there. It's creating an instance and throwing it, not calling a method.
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.
As everyone else has said, instantiate the object before throwing it.
Just wanted to add one bit; it's incredibly uncommon to throw a RuntimeException. It would be normal for code in the API to throw a subclass of this, but normally, application code would throw Exception, or something that extends Exception but not RuntimeException.
And in retrospect, I missed adding the reason why you use Exception instead of RuntimeException; @Jay, in the comment below, added in the useful bit. RuntimeException isn't a checked exception;
- The method signature doesn't have to declare that a RuntimeException may be thrown.
- Callers of that method aren't required to catch the exception, or acknowlege it in any way.
- Developers who try to later use your code won't anticipate this problem unless they look carefully, and it will increase the maintenance burden of the code.