Java, Software Development

Java Null Pointer Exception Processing With Try-Catch

In Java, we can handle exceptional events using the try-catch. But not all exceptions are the same. Java Null Pointer Exception processing requires using try-catch in a way that is unchecked during compilation.

Checked And Unchecked Java Exceptions

We refer to exceptional events in Java as Exceptions, and Java represents them with the java.lang.Exception class. Exceptions can either be Unchecked or Checked Exceptions.

Checked Exceptions are types of Java Exceptions that we explicitly declare to throw and explicitly need to handle. The Java compiler checks for their explicit Exception processing. If we claim to throw Checked Exceptions but do not manage them, the codes will not compile. Checked exceptions still happen at runtime, but the handling of exceptions must be explicit in the code before we run the application.

On the other hand, Unchecked Exceptions are Exceptions that the Java compiler does not check for explicit exception handling or processing even if we expressly declare to throw them. Meaning, we do not need to handle even the possibility of exceptions in the codes explicitly.

Checked exceptions are the Exception class and all its subclasses. Meanwhile, unchecked exceptions are Error, RuntimeException, and their subclasses.

Create Null Pointer Exception In Java

Creating Null Pointer Exceptions in Java is easy. Consider the following codes.

When we run these codes, we get the following runtime error.

We do not need a try-catch to compile the codes. The java.lang.NullPointerException is a subclass of RuntimeException class.

Java Null Pointer Exception Processing

To handle NullPointerException, we can use a try-catch that catches for Exception or RuntimeException. Consider the following codes that catch Exception.

If we want to catch RuntimeException, we change the try-catch as follows.

Alternatively, we can catch NullPointerException. But the Null Pointer Exception is not something we explicitly throw in our Java codes. Also, it may come from some convoluted codes with erring logic. Therefore, it is better to use Exception instead. That way, we capture all exceptions that are subclasses of Exception, including the subclasses of RuntimeException.

This post is part of a reboot Java tutorial.

You Might Also Like