Intermediate 25 min read

Common Built-In Exceptions

By the end of this lesson, you'll be able to:

  • Recognize NullPointerException, MathException, and ListException by name and cause
  • Predict which built-in exception a given piece of code would throw
  • Catch a specific exception type rather than a generic one when possible

Prerequisites: "Try, Catch, and Finally"

NullPointerException

Student student;
System.debug(student.getName()); // NullPointerException

Thrown when code tries to call a method or access a field on something that's null — there's no actual object there to act on. This is the single most common runtime exception in Apex, and the null-check guards from Module 12's "Handle Errors Gracefully" lesson exist specifically to prevent it.

MathException

Decimal result = 10 / 0; // MathException

Thrown by invalid arithmetic — division by zero being the classic case, first seen back in Module 8's calculator project.

ListException

List<String> names = new List<String>{'Amara', 'Ben'};
System.debug(names[5]); // ListException: index out of bounds

Thrown when code tries to access a list index that doesn't exist — here, index 5 when the list only has indexes 0 and 1.

Catching a specific type vs a generic one

try {
    Decimal result = 10 / 0;
} catch (MathException e) {
    System.debug('Specifically a math problem: ' + e.getMessage());
} catch (Exception e) {
    System.debug('Some other problem: ' + e.getMessage());
}

Catching the specific exception type (MathException) first lets you react precisely to the failure you actually expect; a trailing generic catch (Exception e) acts as a catch-all safety net for anything else. Apex checks catch blocks top to bottom, matching the first one whose type fits — the same ordering logic as an if/else if chain from Module 6.

Exercise

As a comment, name which built-in exception type each of these would throw: (1) calling a method on a null variable, (2) accessing List index 10 on a 3-item list.

Show hint

NullPointerException and ListException.

APEX

Common Built-In Exceptions Quiz

1. What causes a NullPointerException?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Apex ships with several built-in exception types for common failure modes — recognizing them by name makes debug logs far faster to read.