Exceptions

A failure is an object, and you catch it narrowly.

An exception is an object that interrupts the normal flow of a method. throw new IllegalArgumentException("bad") says: this value must not be accepted. A NullPointerException is most often a defect, not a working answer. You do not catch it to substitute a zero. You prevent it with a check earlier.

Catch a specific type. catch (Exception ex) around a whole method hides a typo, a dropped connection and your own bug alike. When parsing a number, catch NumberFormatException. At a narrow spot, catch what you know how to turn into an answer for the user.

The compiler forces you to declare or catch checked exceptions. RuntimeException and its subclasses are not checked. The debate about which is better is long. A practical rule: at the input boundary, turn foreign text into a clear result; do not drag a raw exception through ten layers if the outside world will get a 400 anyway.

In the task, bad text becomes the string bad, and a good number is returned as text. The method does not terminate the process. A service that calls System.exit on one malformed field takes down every other client on that thread.

Practice

  1. What to catch

    Parsing a number may throw NumberFormatException. What should you catch?

    • Throwable around main
    • NumberFormatException
    • only ThreadDeath
    • nothing, let the process crash
  2. What null is not

    Is unboxing an Integer that holds null the same as zero? Answer yes or no.

  3. Integers only

    Write static String number(String s). Return an integer as a decimal string. Any other text is bad. The method must not throw outward.