Common Java
Exceptions
Learn to recognize, understand, and handle the most frequent runtime exceptions in Java: NullPointerException, IndexOutOfBoundsException, and NumberFormatException.
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
Why These Three Matter
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.
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 \).
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.
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
java.lang.NullPointerExceptionHow to Prevent Exceptions
if (obj != null) guard.arr[i], confirm that \( i \geq 0 \) and \( i < \text{arr.length} \).Integer.parseInt(s), check that the string is not empty and contains only digits (optionally a leading minus sign).try block and handle the specific exception in the catch block.Example: Spotting the NPE
Example: The Off-by-One IOOBE
Example: Parsing User Input
The try-catch Flow
Common Mistakes
catch (Exception e) hides which specific exception occurred. Always catch the specific exception type.catch (NullPointerException e) { } silently swallows errors. At minimum, log the exception or print a message.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();
.length() on a null reference always throws a NullPointerException. The variable s was never assigned an actual String object.Question 2 of 5
Given int[] arr = new int[5];, which index access will throw an IndexOutOfBoundsException?
arr[5] is out of bounds because the maximum valid index is \( 5 - 1 = 4 \).Question 3 of 5
Which of the following will throw a NumberFormatException?
Integer.parseInt() expects a whole number string. The string "3.14" contains a decimal point, which is not valid for integer parsing. Use Double.parseDouble() for decimals instead.Question 4 of 5
Code snippet:
ArrayList<String> list = new ArrayList<>();
list.add("alpha");
list.add("beta");
String val = list.get(2);
What happens when this code runs?
list.get(2) attempts to access index 2, which does not exist, throwing an IndexOutOfBoundsException.Question 5 of 5
Which is the best way to prevent a NullPointerException when using a method parameter?
Exception broadly is bad practice, declaring it changes nothing (it's unchecked), and for-each loops don't address null references.