01 / 21

Common Java
Exceptions

Learn to recognize, understand, and handle the most frequent runtime exceptions in Java: NullPointerException, IndexOutOfBoundsException, and NumberFormatException.

Java

What Is an Exception?

An exception is an event that disrupts the normal flow of a program during execution. When something goes wrong at runtime, Java creates an exception object containing information about the error: its type, message, and where it occurred.

If an exception is not caught (handled), the program crashes and prints a stack trace to the console: a detailed breadcrumb trail showing exactly which line triggered the error.

The Exception Hierarchy

Throwable Error Exception RuntimeException NullPointerException IndexOutOfBoundsException NumberFormat Exception

Why These Three Matter

NullPointerException
The single most common Java exception. Thrown when you call a method or access a field on a reference that is null.
IndexOutOfBoundsException
Thrown when you access an array or list with an index that is negative or too large for its size.
NumberFormatException
Thrown when a string that does not represent a valid number is passed to a parsing method like Integer.parseInt().

NullPointerException Explained

A NullPointerException (NPE) occurs when your code tries to use an object reference that points to null: calling a method, accessing a field, or getting the length of a null array.

String name = null; int len = name.length(); // NPE thrown here!

IndexOutOfBoundsException Explained

This exception is thrown when you try to access an element at an invalid index. For an array of length \( n \), valid indices are \( 0 \) through \( n - 1 \).

int[] scores = {90, 85, 72}; // length = 3 int val = scores[3]; // IOOBE! Max index is 2
90 [0] 85 [1] 72 [2] ??? [3] OUT OF BOUNDS

NumberFormatException Explained

A NumberFormatException is thrown when you try to convert a String to a number, but the string doesn't contain a valid numeric value.

String input = "hello"; int num = Integer.parseInt(input); // NFE thrown! // These also throw NFE: Integer.parseInt(""); // empty string Integer.parseInt("12.5"); // decimal for parseInt

Key Distinctions

Feature NPE IOOBE NFE
Trigger Using a null reference Bad index Invalid string
Data Structure Any object Array or List String to number
Common Fix Null check Bounds check Input validation
Checked? No (runtime) No (runtime) No (runtime)

Reading a Stack Trace

Exception in thread "main" java.lang.NullPointerException at MyClass.processName(MyClass.java:15) at MyClass.main(MyClass.java:8)
1
Exception type: The first line names the exception: java.lang.NullPointerException
2
Top of the stack: The line directly below the exception is where the error actually happened: line 15 of MyClass.java
3
Call chain: Read downward to trace which method called which: main called processName

How to Prevent Exceptions

1
Check for null: Before using any object reference, verify it is not null with an if (obj != null) guard.
2
Validate indices: Before accessing arr[i], confirm that \( i \geq 0 \) and \( i < \text{arr.length} \).
3
Validate input strings: Before calling Integer.parseInt(s), check that the string is not empty and contains only digits (optionally a leading minus sign).
4
Use try-catch as a safety net: Wrap risky code in a try block and handle the specific exception in the catch block.

Example: Spotting the NPE

public class Student { String name; public static void main(String[] args) { Student s = new Student(); // s.name was never assigned, so it is null System.out.println(s.name.toUpperCase()); } }

Example: The Off-by-One IOOBE

String[] fruits = {"apple", "banana", "cherry"}; for (int i = 0; i <= fruits.length; i++) { System.out.println(fruits[i]); } // Crashes when i = 3 (length is 3, max index is 2)

Example: Parsing User Input

Scanner sc = new Scanner(System.in); System.out.print("Enter your age: "); String input = sc.nextLine(); // User types "twenty" instead of "20" int age = Integer.parseInt(input); // NFE!
try { int age = Integer.parseInt(input); System.out.println("Age: " + age); } catch (NumberFormatException e) { System.out.println("Invalid input!"); }

The try-catch Flow

try { code } Exception? No Continue normally Yes catch { handle } finally { always runs }

Common Mistakes

✕ Catching too broadly
Writing catch (Exception e) hides which specific exception occurred. Always catch the specific exception type.
✕ Empty catch blocks
Writing catch (NullPointerException e) { } silently swallows errors. At minimum, log the exception or print a message.
✕ Ignoring the stack trace
Students skip reading the trace and guess randomly. The top line tells you exactly where the error is.
✕ Calling .equals() on null
A common error is writing myString.equals("text") when myString might be null, causing an NPE. The safe way is "text".equals(myString).

Quick Reference Summary

Exception Cause Prevention
NullPointerException Calling methods on null if (x != null)
IndexOutOfBoundsException Index \( < 0 \) or \( \geq \text{length} \) Check \( i \geq 0 \) and \( i < \text{len} \)
NumberFormatException Non-numeric string parsed try-catch or validate

Question 1 of 5

What exception is thrown by the following code?
String s = null; s.length();

Question 2 of 5

Given int[] arr = new int[5];, which index access will throw an IndexOutOfBoundsException?

Question 3 of 5

Which of the following will throw a NumberFormatException?

Question 4 of 5

What happens when this code runs?

Question 5 of 5

Which is the best way to prevent a NullPointerException when using a method parameter?