Course topics

By WebNest Studio Engineering Team

Java - Core Tutorial

Exception Handling Basics

An exception is an event that disrupts the normal flow of a program's instructions, occurring during execution because of something abnormal — a missing file, an invalid array index, dividing by zero, or a null reference being used. Instead of letting the program crash immediately with no explanation, Java represents this event as an object and gives you a structured mechanism to detect it, react to it, and keep the rest of the program running safely.

Java forces you to deal with certain categories of exceptions at compile time. This is a deliberate design decision, not an accident: Sun Microsystems wanted large, long-lived Java programs to fail predictably and recoverably rather than silently or catastrophically. When a method can encounter a condition it cannot resolve on its own — a network call timing out, a file that doesn't exist — Java requires that this possibility be visible in the code, either by handling it or explicitly declaring it, so it can never be "forgotten" by whoever calls that method.

Why it matters

Real programs meet bad input, missing files and failed network calls every day. Without exception handling, the first such problem stops the whole program with a stack trace. With it, you decide what happens instead: report the problem, try something else, or carry on with the next item. That difference is what separates a script from software people can rely on.

Why Exceptions Exist

Without exceptions, error handling would rely on return codes (like -1 or null) that calling code could easily ignore. Exceptions separate the error-handling logic from the normal logic of a program: the code that detects a problem does not need to know how to fix it, and the code that knows how to recover does not need to be tangled into every line where a failure might occur.

  • Detection — the JVM or your code identifies an abnormal condition and creates an exception object describing it.
  • Propagation — if not handled immediately, the exception travels up the call stack, unwinding method calls until something catches it.
  • Handling — a catch block (or the JVM itself, as a last resort) processes the exception, potentially recovering, logging, or terminating gracefully.

What Happens Without Handling

If an exception is never caught anywhere in the call stack, it reaches the JVM's default handler, which prints a stack trace to the console (showing the exception type, its message, and the exact sequence of method calls that led to it) and terminates that thread. This is why unhandled exceptions in a program's main method cause it to stop and print a trace instead of continuing.

Example

An unhandled exception versus a caught one

Java
public class BasicsDemo {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30};

        try {
            System.out.println(numbers[5]); // invalid index
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught: " + e.getMessage());
        }

        System.out.println("Program continues normally.");
    }
}
Output
Caught: Index 5 out of bounds for length 3
Program continues normally.

Common Mistakes

  • Assuming an exception automatically stops the whole program — only an uncaught exception on a given thread does that; a caught one lets execution continue.
  • Treating exceptions as "just errors to avoid" instead of a structured signal that something specific and identifiable went wrong.
  • Ignoring the stack trace and only reading the exception message — the trace tells you exactly where the failure originated.

Exercise

Write divide so that dividing by zero does not crash the program. When the divisor is zero it should print a message and return 0, and the program should carry on to its last line.

Expected output: 5, Cannot divide by zero, 0, Done

Java · starter code
public class SafeDivide {

    static int divide(int a, int b) {
        // TODO: return a / b, but catch ArithmeticException,
        // print "Cannot divide by zero" and return 0
        return a / b;
    }

    public static void main(String[] args) {
        System.out.println(divide(10, 2));
        System.out.println(divide(10, 0));
        System.out.println("Done");
    }
}
Show hints
  • Put the division inside a try block and handle ArithmeticException in the catch.
  • After the catch block runs, the method continues normally, so return a value from it.
Show solution
Java · solution
public class SafeDivide {

    static int divide(int a, int b) {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
            return 0;
        }
    }

    public static void main(String[] args) {
        System.out.println(divide(10, 2));
        System.out.println(divide(10, 0));
        System.out.println("Done");
    }
}

Quick quiz

1. What happens when Java evaluates the integer expression 10 / 0?

  • A. It returns 0
  • B. It throws ArithmeticException
  • C. It returns Infinity
  • D. It does not compile
Show answer

B. Integer division by zero throws ArithmeticException. Only floating-point division by zero gives Infinity.

2. An exception is thrown in main and nothing catches it. What happens?

  • A. The program continues with the next line
  • B. The exception is ignored
  • C. The thread ends and the JVM prints a stack trace
  • D. The program restarts
Show answer

C. An uncaught exception terminates the thread. The default handler prints the exception and its stack trace.

3. After a catch block has handled an exception, where does execution continue?

  • A. At the line that threw the exception
  • B. At the start of the try block
  • C. It stops
  • D. After the whole try-catch statement
Show answer

D. The rest of the try block is skipped. Once the catch finishes, execution carries on after the try-catch.

Interview questions

What is an exception?

Show answer

An exception is an object that represents an abnormal event which interrupts the normal flow of a program, such as invalid input or a missing file. When one is thrown, the JVM stops executing the current code and looks up the call stack for a matching catch block. If none is found, the thread ends.

What information does a stack trace give you?

Show answer

The exception type and message on the first line, followed by the chain of method calls that were active when it was thrown, most recent first, each with a class, method, file and line number. Reading from the top, the first line that belongs to your own code is usually where to start looking.

Key Points to Remember

  • An exception is an object representing an abnormal event that disrupts normal program flow.
  • Unhandled exceptions propagate up the call stack until caught, or reach the JVM and terminate the thread with a stack trace.
  • Java requires certain exceptions to be handled or declared, forcing failure paths to be visible in code rather than silently ignored.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering