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 :-(
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.
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.
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.
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.
Link to the tutorials for completeness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With