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 : StackOverFlowError
.
Both Exception
and Error
are Java Objects and they extend from the java.lang.Throwable
class.
There are two broad categories of exceptions in Java:
RuntimeException, Error
and their subclasses fall under this category. For example : SQLException, ClassNotFoundException, IOException
etc.ArrayIndexOutOfBoundsException, ArithmeticException, NullPointerException
etc.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.Throwable
class 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 Throwable
class.
//Returns the message text describing the exception String getMessage(){ ............ } //Prints the stack trace of the exception void printStackTrace(){ ...... }
java.lang.RuntimeException
and all of its subclasses are unchecked/runtime exceptions which usually occur due to programming errors which should not occur in the first place.ArithmeticException
.Short
object to Integer
object etc.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.Error
class 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!