Exception Handling in Java

Recently I have been learning how to use the exception handling types in Java’s JDK more appropriately.

Here are some golden rules to follow, when throwing an exception type. Much of how you use checked and unchecked exception types, depends on where you want to throw an exception in the application’s stack.

IllegalArgumentException

  • Used and useful when parsing an object or string that fails.
  • A good example could be validating whether a URL or email matches a given format.

NullPointerException

  • A difficult exception to throw compared to IllegalArgumentException.
  • It’s recommended you stay away from using them.
  • You do not want to mix bad NPEs with NPEs thrown intentionally.
  • It is recommended you throw IllegalArgumentException instead.
  • Just return null when encountering a value that has not been set.

RuntimeException

  • The foundational (base) exception class in Java.
  • It is commonly used to catch unchecked exceptions.
  • It is particularly useful to throw, when processing something at a higher level, for instance, parsing with an external properties file.
  • It is common to extend a custom exception class using the RuntimeException class, since it is considered best practice to do so, unless extending a super class with more unique exception handling capabilities.
This entry was posted in Java, Software Engineering. Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>