Java Tutorial

Exceptions

try/catch, checked vs unchecked, and custom exception handling

What are Java Exceptions?

In Java, an exception is a special object that indicates that something went wrong during the execution of your program. If not "caught" or "handled", it will cause the program to crash. Errors are not your enemy—they are a guide to identifying and fixing bugs!
java
// A simple exception (ArithmeticException!)
// System.out.println(10 / 0);

// Handle it!
try {
  System.out.println(10 / 0);
} catch (ArithmeticException e) {
  System.out.println("Error caught: Don't divide by zero!");
}
// 1. "Error caught: Don't divide by zero!" (Program continues!)

Handling Exceptions with try/catch/finally

  • try: Block of code you want to "monitor" for errors.
  • catch(err): Block that runs ONLY if a specific error occurs.
  • finally: Block that runs no matter what, whether an error occurred or not. Use this for cleanup logic (like closing a file or hiding a loading spinner).
java
try {
  // Logic that might fail
  int res = divide(10, 0);
} catch (Exception e) {
  // Handle the error!
  System.err.println("Task failed: " + e.getMessage());
} finally {
  System.out.println("Process complete.");
}

Creating Custom Exceptions

For large-scale projects, it's often more descriptive to create your own Exception types.
java
// Customize by inheriting from the base 'Exception' class
public class DatabaseException extends Exception {
    public DatabaseException(String message) {
        super(message);
    }
}

// throw new DatabaseException("Cannot connect!");

Comparisons: Checked vs. Unchecked

Wait! Java is unique because it has two types of exceptions:
TypeExamplesDescription
CheckedIOException, SQLExceptionMUST be handled (or declared) or the code won't compile!
UncheckedNullPointerException, IndexOutOfBoundsCaused by logic bugs. You don't HAVE to handle them manually.

The "throws" Keyword

If a method knows it might fail with a Checked Exception, but doesn't want to handle it itself, it must "declare" that to anyone who calls it.
java
// I might throw a checked exception!
public void readFile() throws IOException {
    // ... file logic ...
}

Summary

TermDescription
tryMonitor for crashes
catchRecover from errors
finallyFinal cleanup logic
throwManually trigger an error
throwsDeclare that a method could fail
CheckedExceptions the compiler FORCES you to handle
UncheckedRuntime exceptions (usually programming bugs)
Best ForBug prevention, resilient code, input validation
SafePreventing crashes in production environments
Loge.printStackTrace() (The original way to find bugs!)
Moderntry-with-resources (Java 7+) to auto-close files!
HandleDon't catch an exception and do NOTHING! (Always log it!)
ExceptionThe base object for all handleable errors
ErrorCritical system issues (e.g., OutOfMemory) — DO NOT catch these!
MessageThe descriptive string of the error (e.g., "Divide by zero")
CauseHigher-level exceptions can "wrap" lower-level ones
StackThe chain of calls that led to the crash
SearchThe JVM looks for the nearest catch block on the stack
Multiple`catch (IOException
SecurityNever expose internal stack traces to the end-user!
TestingUnit tests should "expect" specific exceptions to occur
StandardEstablished and trusted worldwide for 25+ years
RuntimeRuntimeException is the parent of all Unchecked exceptions
SafetyCompiler will NOT let you use a variable if its creation might fail!
HierarchyParent-child links for catching groups of errors
ResourceUse try (File f = ...) {} to prevent leaks!
CustomUse them for clear domain-specific business errors