Nullpointerexception is an example of unchecked exception

Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.

Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.

The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly. For example, a method can check if one of its arguments is incorrectly null. If an argument is null, the method might throw a NullPointerException, which is an unchecked exception.

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Some exceptions in Java must be handled in the developer's code. Other exceptions can occur without any exception handling semantics at all. When an exception must be handled with try-and-catch semantics, it is known as a checked exceptions. If try-and-catch semantics are not required, it is known as an unchecked exception.

Checked exception example

A checked exception in Java represents a predictable, erroneous situation that can occur even if a software library is used as intended.

For example, if a developer tries to access a file, the Java IO library forces them to deal with the checked FileNotFoundException. The developers of the Java IO API anticipated that attempting to access a file that does not exist would be a relatively common occurrence, so they created a checked exception to force a developer to deal with it.

Unchecked exception example

In contrast to a checked exception, an unchecked exception represents an error in programming logic, not an erroneous situation that might reasonably occur during the proper use of an API.

Because the compiler can't anticipate logical errors that arise only at runtime, it can't check for these types of problems at compile time. That's why they are called "unchecked" exceptions.

Unchecked exceptions result from faulty logic that can occur anywhere in a software program. For example, if a developer invokes a method on a null object, an unchecked NullPointerException occurs. If a developer attempts to access an array element that does not exist, the unchecked ArrayIndexOutOfBoundsException occurs.

Compare checked vs. unchecked exceptions

Criteria Unchecked exception Checked exception
Purpose Unanticipated errors in logic that show up at runtime Anticipated problems associated with the normal use of an API
Ancestry Includes RuntimeException Does not include RuntimeException
Handling Exception handling semantics are not required Must be handled in a try-and-catch block, or be thrown by the invoking method
Extension Can be customized by extending RuntimeException Can be customized by extending java.lang.Exception
List of examples NullPointerException, ClassCastException, ArithmeticException, DateTimeException, ArrayStoreException ClassNotFoundException, SocketException, SQLException, IOException, FileNotFoundException

Handling checked and unchecked exceptions

The following example contrasts checked and unchecked exceptions.

public static void main(String[] args) {
 
 /* checked vs unchecked exception example */
 try {
  Class.forName("com.mcnz.Example");
 } catch (ClassNotFoundException e) {
  System.out.println("Class was not found.");
 }
    
 String input = null;
 input.length(); // throws an unchecked exception
    
}

First, the Class.forName() method loads the class named com.mcnz.CheckedClass into the JVM. The API developer knows there's a possibility that the class may not exist, so the developer is forced to handle the ClassNotFoundException through try-and-catch semantics.

As the code executes, the forName() method may never actually throw a ClassNotFoundException. Nevertheless, the developer is forced to handle this checked condition.

Now look at the assignment of the String named input to null, and the subsequent length(). This input.length() invocation triggers a NullPointerException and causes the program to fail every time it runs. This is an unchecked exception caused by poor programming practices that are not revealed until the program executes. Therefore, it requires no exception handling semantics.

Modern use of unchecked exceptions

The technical description of checked vs. unchecked exceptions provided in this article are in line with the manner in which the creators of the Java language envisioned their use. However, the syntactic ceremony associated with handling checked exceptions, especially when there is little chance to recover from them, tends to make Java code more verbose, less readable and more difficult to maintain.

The general trend in the industry is to move away from the extensive creation of checked exceptions in an API or framework.

Many frameworks, including Spring, simply capture checked exceptions and then rethrow them as unchecked exceptions. A global exception harness then catches all unchecked exceptions and performs generic exception handling and recover routines.

What type of exception is NullPointerException?

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

Why null pointer is an unchecked exception?

It's not a checked exception (among other things) because it is extremely common. It can occur pretty much everywhere. If it were checked, then nearly every single method in every single Java program anywhere would have to declare that it throws NullPointerException .

What is NullPointerException example?

NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value. For example, using a method on a null reference.

What are unchecked exceptions?

An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.