Java Exception framework helps us to handle exceptions in Java very effectively and without much pain. In this post, we’ll learn about Exceptions in Java, their types, the difference between checked and unchecked exceptions. We’ll also cover significantly good number of classes available in Java Exception framework.
Exceptions are abnormal disruptions in the normal execution flow of a program mostly due to failing semantic requirements. For instance, intended file was not found in the expected location or the object reference is null. Java provides excellent support for handling exceptions.
Exceptions shouldn’t be confused with errors. Errors indicate that something severely wrong has happened. It usually leads to application being crashed as by no means it can be handled within our code. For example :
Error are Java Objects and they extend from the
There are two broad categories of exceptions in Java:
RuntimeException, Errorand their subclasses fall under this category. For example :
SQLException, ClassNotFoundException, IOExceptionetc.
ArrayIndexOutOfBoundsException, ArithmeticException, NullPointerExceptionetc.
Let’s have a look at some of the most common exception classes that we might come across from time to time.
Nugget : Not all exception classes belong to java.lang language.
java.lang.Throwableclass is the super class of all the exception/error related classes in the Java exception handling framework. All classes of throwables define a single parameter constructor which takes in a string argument referring to the exception message text. Below are the two commonly used methods available in
//Returns the message text describing the exception
//Prints the stack trace of the exception
java.lang.RuntimeExceptionand all of its subclasses are unchecked/runtime exceptions which usually occur due to programming errors which should not occur in the first place.
java.time.format.DateTimeFormatter.ofPattern(String pattern)methods throws this exception when supplied an invalid pattern.
IllegalArgumentException. It is thrown when the conversion from string to a numeric value is not possible.
Errorclass along with its subclasses define irrecoverable conditions that cannot be handled in a program.
Today we covered what exceptions mean and how they are different from errors. We also looked at the types of exceptions – checked and unchecked exceptions.
We have looked at a significant number of classes from Java Exception framework. In the upcoming posts, we’ll learn how to handle exceptions in Java using
try, catch and finally. Please feel free to check it out!