When to throw runtime exception?

Should we actually throw runtime exception?

Yes, we should. Runtime exception serve a specific purpose – they signal programming problems that can be fixed only by changing code, as opposed to changing the environment in which the program runs.

Under what conditions should actually throw a runtime exception?

When you detect an error with the way your class or method is used, throw a runtime exception.

Generally, there are two categories of situations when you need to throw a runtime exception:

  • Passing invalid parameter values – This is the most common cause of runtime exceptions. Most parameter validation exceptions should be runtime exceptions. Java provides several subclasses to signal these specific problems.
  • Calling methods in a wrong sequence – This is another common cause. When certain methods cannot be called until a class finishes initialization or some other preparatory steps, calls at the wrong time should cause runtime exceptions.

In this sense, your code is fine: it fits squarely in the first category, i.e. passing invalid parameter values. One thing I would do slightly differently is adding a message to say which parameter had an invalid value, but in your case it is not critical, because there is only one parameter there.

Leave a Comment

tech