Built-in Exception Types in Java
Java's standard library ships a large set of ready-made exception types covering common failure situations, so most everyday problems don't require defining a custom exception at all: NullPointerException for calling a method or accessing a field on a null reference, ArrayIndexOutOfBoundsException for an invalid array index, ArithmeticException for something like integer division by zero, ClassCastException for an invalid cast between incompatible types, and NumberFormatException for failing to parse text as a number.
Reaching for the most specific, already-accurate built-in exception type — rather than a generic RuntimeException with just a custom message — gives calling code a much more useful signal, since catching code can distinguish a NumberFormatException from a NullPointerException without inspecting message text at all. A well-chosen existing type also means less code to write and maintain than a needless custom one.
NullPointerException
Thrown when calling a method or accessing a field on a reference that's actually null.
ArrayIndexOutOfBoundsException
Thrown when an array is accessed with an index outside its valid range.
ArithmeticException
Thrown for invalid arithmetic, most commonly integer division by zero.
ClassCastException
Thrown when an invalid cast is attempted between two incompatible types at runtime.
NumberFormatException
Thrown when text that doesn't represent a valid number is parsed as one, like Integer.parseInt("abc").
public class BuiltinExceptionDemo { public static void main(String[] args) { try { int value = Integer.parseInt("not a number"); } catch (NumberFormatException e) { System.out.println("Caught: " + e.getMessage()); } }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.