Course contentsShow
← Java
Lesson 790 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

When to Use Unchecked Exceptions: Programming Errors

Learn to use unchecked exceptions for programming bugs like null pointers, illegal arguments, or invalid state that shouldn't be caught.

When to Use Unchecked Exceptions: Programming Errors

You'll learn when unchecked exceptions are the right choice for representing bugs that developers should fix, not catch.

The Purpose of Unchecked Exceptions

Unchecked exceptions signal programming errors—mistakes in your code's logic that shouldn't happen if the program is written correctly. These are bugs like accessing a null reference, passing an invalid argument, or calling a method when the object isn't in the right state.

Think of unchecked exceptions like smoke alarms in a building. You don't plan for fires or build "fire-handling" into normal operations—you fix the wiring, store flammables properly, and prevent fires. Similarly, you shouldn't catch unchecked exceptions; you should fix the bug that causes them.

Common Programming Errors Represented by Unchecked Exceptions

NullPointerException: You tried to use an object reference that's null. This means you forgot to check for null or initialize something properly.

IllegalArgumentException: You passed an invalid argument to a method. The caller violated the method's contract (like passing a negative number where only positive values make sense).

IllegalStateException: You called a method when the object wasn't ready for it. For example, trying to read from a closed connection.

IndexOutOfBoundsException: You accessed an array or list with an invalid index. This is a logic error in your loop or calculation.

Why Not Catch Them?

These exceptions indicate your code is broken. Catching them hides the problem instead of fixing it. When you see a NullPointerException, the solution isn't try-catch—it's fixing the null reference bug.

Key Takeaway: Use unchecked exceptions for programming bugs that represent developer mistakes requiring code fixes, not runtime handling. They shouldn't be caught—they should be prevented through correct programming.