Runtime exceptions indicate broken contract (like NPE) and should never be thrown if code has no errors. It always indicates error in code (same as asserts but asserts are for internal class errors while Runtime are for class's client errors).
Runtime exceptions should never be catched.
Checked exceptions, on the other hand, are part of signature and should be catched and processed. They may indicate user input errors or external resource troubles (like IOException
).
With all of it I can't get why NumberFormatException
is runtime?
Runtime errors occur when something goes wrong in the normal execution of a program. When severe enough, these errors abruptly terminate an application. To help programmers both anticipate and recover from runtime errors, the Java programming language defines a special class named the RuntimeException.
How to handle NumberFormatException. Use try and catch block surrounding the code that can cause NumberFormatException. ) Another way of handling the exception is the use of throws keyword.
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. RuntimeException and its subclasses are unchecked exceptions.
The IllegalArgumentException class is a superclass of the NumberFormatException as it is an unchecked exception, so it is not forced to handle and declare it.
Firstly, whoever told you
Runtime exceptions should never be caught
doesn't know much about Java. Don't listen to them - they are wrong.
NumberFormatException being a runtime exception: Unchecked exceptions are chosen because they indicate a programming error. It is possible to know before calling Integer.parseInt()
(for example) that a String is a valid integer number, e.g. here's just one way:
if (str.matches("^\\d{1,8}$") { int myInt = Integer.parseInt(str); // will never throw NumberFormatException }
Therefore, it can be considered a programming error to ever get one - the programmer chose to not check first.
If you are not confident about the integrity/quality of the String you are about to parse, it's easy to catch:
try { // parse your string } catch (NumberFormatException e) { // do something about it }
The other reason to make it a runtime is that it doesn't clutter the code with potentially unnecessary try/catch
blocks, if you are confident that you won't get one, e.g. if to totally trust the source of the String data.
NumberFormatException
could also be thrown when parsing configuration files, in which case it would be a programmer error. When parsing user input you are usually using NumberFormat
which throws a checked ParseException
.
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