That's because it's an unchecked exception. It doesn't need to be explicitly declared or catched. Also see the Java tutorial on the subject.
In general, you should only throw a RuntimeException
(preferably one of its "Direct Known Subclasses" listed in the javadoc) to signal that the caller is doing it wrong. E.g. when the caller incorrectly passes a null
argument (then throw NullPointerException
), or an illegal argument (then throw IllegalArgumentException
), or when the caller invokes the method at the wrong moment/state (then throw IllegalStateException
), etcetera. The caller is supposed to fix their code to avoid that. E.g. checking beforehand if the argument is not null, or if the argument is in correct format/syntax, or ensuring that the method is called at the right moment.
If there is a specific situation which should throw a runtime exception and you can't use one of its specific subclasses, then you are supposed to extend it and document it properly in the new exception's javadoc and in the calling method, e.g. ConfigurationException extends RuntimeException
for the case that the calling code hasn't configured the application/API properly before use. This should signal the enduser (the other developer) sufficiently to take action accordingly.
In a nutshell:
RuntimeExceptions
should identify programmatically recoverable problems which are caused by faults in code flow or configuration under control of code developer (read: developer's faults).
- Checked
Exceptions
should identify programmatically recoverable problems which are caused by unexpected conditions outside control of code developer (e.g. database down, file I/O error, wrong enduser input, etc).
Errors
should identify programmatically unrecoverable problems outside control of code developer (e.g. out of memory, exception inside an initializer, etc).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…