Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 28: Exception Handling Basics in Java

Java for Beginners · Module 5: Data and Methods


🎯 When Things Go Wrong at Run Time

In earlier lessons you saw programs crash with messages like ArithmeticException or NumberFormatException. These crashes are called exceptions. Instead of letting the program die, Java lets you catch an exception and decide what to do next. That is exception handling.

📌 An exception is an event that disrupts normal flow at run time. try holds risky code, catch handles a specific problem, and finally runs cleanup code whether or not an error occurred.
ExceptionTypical causeSeen in
ArithmeticExceptioninteger divided by 0Lesson 12
ArrayIndexOutOfBoundsExceptionarray index too big or negativeLesson 21
StringIndexOutOfBoundsExceptionbad String indexLesson 23
NullPointerExceptionmethod called on nullLesson 23
NumberFormatExceptionparseInt on text like “abc”Lesson 9
InputMismatchExceptionScanner got the wrong kind of inputLesson 10
StackOverflowErrorrecursion with no base case (an Error)Lesson 26

Figure 3: Exceptions you have already met in this series.

1️⃣ try and catch

try
code that may fail
error?
catch
handle the error
always
finally
cleanup, runs either way
If the try block finishes with no error, the catch block is skipped. The finally block runs in both cases.

Figure 1: The flow of try, catch and finally.

public class TryCatch {
    public static void main(String[] args) {
        try {
            int a = 10, b = 0;
            System.out.println("before division");
            int c = a / b;
            System.out.println("result = " + c);
        } catch (ArithmeticException e) {
            System.out.println("Caught: " + e.getMessage());
        }
        System.out.println("program continues");
    }
}
🖥️ Output:
before division
Caught: / by zero
program continues
  • When a / b fails, Java jumps out of the try block at once. The line result = ... never runs.
  • The matching catch block receives the exception object e. e.getMessage() gives a short description.
  • After the catch, the program carries on normally. Without the try-catch it would have stopped.

2️⃣ Several catch Blocks and finally

public class MultiCatch {
    static void test(String text, int index) {
        try {
            int n = Integer.parseInt(text);
            int[] arr = {10, 20, 30};
            System.out.println("arr[" + index + "] / n = " + (arr[index] / n));
        } catch (NumberFormatException e) {
            System.out.println("Not a number: " + text);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Bad index: " + index);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } catch (Exception e) {
            System.out.println("Something else: " + e);
        } finally {
            System.out.println("-- done with (" + text + ", " + index + ")");
        }
    }

    public static void main(String[] args) {
        test("5", 1);
        test("abc", 1);
        test("5", 7);
        test("0", 1);
    }
}
🖥️ Output:
arr[1] / n = 4
— done with (5, 1)
Not a number: abc
— done with (abc, 1)
Bad index: 7
— done with (5, 7)
Cannot divide by zero
— done with (0, 1)
  • One try block can have several catch blocks. Java uses the first one that matches, so list the more specific exceptions first.
  • catch (Exception e) at the end catches any other ordinary exception. Because it is the most general, it must come last.
  • finally runs every time: after a normal finish and after a caught exception. It is the right place to close files or connections.
  • Each of the four test calls shows a different path through the same code.

3️⃣ Throwing Your Own Exceptions

You can raise an exception yourself with throw when your method receives something unacceptable.

public class ThrowDemo {
    static void setAge(int age) {
        if (age < 0 || age > 120) {
            throw new IllegalArgumentException("Invalid age: " + age);
        }
        System.out.println("Age set to " + age);
    }

    static int safeDivide(int a, int b) {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            return 0;
        } finally {
            System.out.println("safeDivide finished");
        }
    }

    public static void main(String[] args) {
        setAge(20);
        try {
            setAge(-5);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
        System.out.println("safeDivide(8, 2) = " + safeDivide(8, 2));
        System.out.println("safeDivide(8, 0) = " + safeDivide(8, 0));
    }
}
🖥️ Output:
Age set to 20
Rejected: Invalid age: -5
safeDivide finished
safeDivide(8, 2) = 4
safeDivide finished
safeDivide(8, 0) = 0
  • throw new IllegalArgumentException(...) stops setAge immediately, and the caller decides how to react.
  • finally runs even though the method returns inside try or catch. Both calls print “safeDivide finished”.

4️⃣ Retrying Until the Input Is Valid

Exception handling combined with a loop (Lesson 18) is the standard way to ask the user again after bad input.

import java.util.Scanner;

public class InputLoop {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = 0;
        while (true) {
            System.out.print("Enter your age: ");
            String line = sc.nextLine();
            try {
                age = Integer.parseInt(line.trim());
                break;
            } catch (NumberFormatException e) {
                System.out.println("Please type digits only.");
            }
        }
        System.out.println("Age = " + age);
    }
}
🖥️ Output (bold = what the user types):
Enter your age: abc
Please type digits only.
Enter your age: 12x
Please type digits only.
Enter your age: 21
Age = 21
  • The program reads the whole line as text, then tries to convert it. This avoids the Scanner newline trap and the InputMismatchException from Lesson 10.
  • When the conversion works, break (Lesson 20) leaves the loop. Otherwise the catch prints a hint and the loop repeats.
  • trim() removes the spaces around ” 21 ” (Lesson 24).

5️⃣ Checked and Unchecked Exceptions

Throwable
Error
serious JVM problems (OutOfMemoryError): do not catch
Exception
problems your program can handle
Checked (compiler forces you to handle)
IOException, FileNotFoundException
Unchecked = RuntimeException
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException

Figure 2: A simplified view of the exception family.

Unchecked exceptions (subclasses of RuntimeException) are usually programming mistakes, so Java does not force you to handle them. Checked exceptions describe problems outside your control, such as a missing file, so the compiler forces you to handle them.

import java.io.FileReader;
import java.io.IOException;

public class Checked {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader("missing.txt");
            fr.close();
        } catch (IOException e) {
            System.out.println("File problem: " + e.getMessage());
        }
    }
}
🖥️ Output (the message text depends on the operating system):
File problem: missing.txt (No such file or directory)
  • Opening a file can fail for reasons the programmer cannot prevent, so Java makes you wrap it in try-catch (or declare throws in the method heading).
  • Files and streams are covered in more depth in the next Java series.

6️⃣ Reading a Stack Trace

main
calls a()
calls b(): exception thrown here
With no catch, the exception travels back up through b, a, main (the stack trace lists them in that order) and the program stops.

Figure 4: An uncaught exception travels up the call stack.

public class Unc {
    static void a() { b(); }
    static void b() { int[] x = new int[2]; x[5] = 1; }
    public static void main(String[] args) {
        System.out.println("start");
        a();
        System.out.println("never printed");
    }
}
🖥️ Runtime error:
start
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 2
at Unc.b(Unc.java:3)
at Unc.a(Unc.java:2)
at Unc.main(Unc.java:6)
  • First line: what went wrong, with the exception name and message.
  • Following lines: where. The top line (Unc.b, line 3) is where it happened. The lines below show who called it.
  • The line “never printed” is skipped because nothing caught the exception.
  • To fix a crash, read the first line, then jump to the first line that names your class.

7️⃣ Errors Beginners Meet at Compile Time

Not handling a checked exception

import java.io.FileReader;

public class Bad1 {
    public static void main(String[] args) {
        FileReader fr = new FileReader("data.txt");
    }
}
🖥️ Compiler message:
Bad1.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(“data.txt”);
^
1 error

A general catch before a specific one

public class Bad2 {
    public static void main(String[] args) {
        try {
            int x = 5 / 0;
        } catch (Exception e) {
            System.out.println("general");
        } catch (ArithmeticException e) {
            System.out.println("specific");
        }
    }
}
🖥️ Compiler message:
Bad2.java:7: error: exception ArithmeticException has already been caught
} catch (ArithmeticException e) {
^
1 error
  • Exception already catches ArithmeticException, so the second block could never run. Put specific catches first.

try with nothing after it

public class Bad3 {
    public static void main(String[] args) {
        try {
            System.out.println("hello");
        }
        System.out.println("no catch");
    }
}
🖥️ Compiler message:
Bad3.java:3: error: ‘try’ without ‘catch’, ‘finally’ or resource declarations
try {
^
1 error

⚠️ Common Mistakes

MistakeProblemFix
Empty catch block: catch (Exception e) { }Hides errors silentlyAt least print the message
Exception caught before specific typesCompile errorMost specific first
Using try-catch instead of checking a simple conditionSlow and unclearCheck b != 0 when you can
Putting too much code in one try blockUnclear which line failedKeep the try block small
Catching Error typesJVM-level problems cannot be fixedCatch Exception types only
Forgetting that code after the failing line is skippedVariables left unsetInitialise before the try

❓ Frequently Asked Questions

Q1. What is the difference between throw and throws?
throw raises an exception at one place. throws in a method heading warns callers that the method may raise a checked exception.

Q2. Does finally run after System.exit()?
No. System.exit stops the JVM immediately.

Q3. Can I catch two exceptions in one block?
Yes: catch (NumberFormatException | ArithmeticException e).

Q4. Can I create my own exception class?
Yes, by extending Exception or RuntimeException. That needs inheritance, which comes in the OOP series.

✅ Key Takeaways

  • Exceptions are run-time problems. try / catch lets the program recover instead of crashing.
  • Order catch blocks from most specific to most general. The first match wins.
  • finally always runs, so use it for cleanup.
  • throw raises your own exception, for example when an argument is invalid.
  • Checked exceptions must be handled or declared. Unchecked ones (RuntimeException) need not be.
  • Read a stack trace from the top: what failed, then where.

🔁 Module 5 Recap

Lessons 21 to 28 covered arrays, strings, methods, recursion, ArrayList and exceptions. You can now store data, process text, split a program into methods and handle errors. In the last module you will meet objects, the idea Java is built around, and then combine everything in mini-programs.

🎓 Practice questions: (1) Write a program that reads two numbers as text and prints their quotient, handling both a non-number and a zero divisor. (2) Why must catch (Exception e) come after catch (ArithmeticException e)? (3) What does finally print in a method that returns inside try? (4) Write a method getElement(int[] a, int i) that returns -1 instead of crashing for a bad index. (5) Read the stack trace of any crash from your own programs and explain each line.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision