⚡0 XP🔥0

Exception Handling

Lesson 12 of 15 ⏱ 6 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Java

try, catch, finally, multiple and multi-catch blocks, checked vs unchecked exceptions, throw and throws, custom exceptions and try-with-resources.

An exception is an event that disrupts the normal flow of a program: dividing by zero, a missing file, invalid input, a null reference. Without handling, the JVM prints a stack trace and stops the program. Exception handling lets you recover gracefully.

try and catch#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
100 / 10 = 10
Cannot divide by 0: / by zero
100 / 5 = 20
Program continues normally

When an exception is thrown inside try, the rest of the try block is skipped and control jumps to the matching catch.

हिंदी में समझें

Exception यानी program चलते समय आई कोई गड़बड़ (zero से भाग, गलत index, file न मिलना)। जिस code में गड़बड़ हो सकती है उसे try में रखें, और catch में बताएँ कि गड़बड़ होने पर क्या करना है। इससे program बीच में crash नहीं होता।

Multiple catch blocks, multi-catch and finally#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
arr[1] / n = 4
  (finally always runs)
Not a number: x
  (finally always runs)
Problem: ArrayIndexOutOfBoundsException
  (finally always runs)
Problem: ArithmeticException
  (finally always runs)

The exception hierarchy: checked vs unchecked#

Throwable
├── Error                      (serious JVM problems: OutOfMemoryError - don't catch)
└── Exception
    ├── IOException, SQLException, ...      ← CHECKED: must catch or declare
    └── RuntimeException                    ← UNCHECKED: usually programming bugs
        ├── ArithmeticException
        ├── NullPointerException
        ├── ArrayIndexOutOfBoundsException
        ├── NumberFormatException
        └── IllegalArgumentException
  • Checked exceptions - the compiler forces you to either catch them or declare them with throws. They represent problems outside your control (files, network, database).
  • Unchecked exceptions (RuntimeException and children) - not enforced; they usually mean a bug to fix (null references, bad indexes).
▶ Try it YourselfJava
Ctrl + Enter to run
Output
NullPointerException - name was never assigned
ClassCastException - a String is not an Integer

throw and throws#

Use throw to raise an exception yourself - typically to reject invalid arguments. Use throws in a method signature to declare checked exceptions the caller must handle:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
OK, balance 3800.0
Rejected: Amount must be positive
Rejected: Insufficient funds: balance 3800.0
Loaded app.cfg
Config error: app.txt not found

Custom exceptions#

Create your own exception classes for business rules. Extend Exception for checked, RuntimeException for unchecked:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
Riya admitted
Not admitted: Marks 54 are below the cut-off of 60 (short by 6)

try-with-resources#

Resources such as files, scanners and database connections must be closed. try (...) closes them automatically, even if an exception occurs:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
> Lesson 1: Basics
> Lesson 2: OOP
missing.txt does not exist
Tip

Good practice: catch the most specific exception you can handle, never swallow exceptions with an empty catch {}, include helpful messages, and don't use exceptions for normal control flow (check hasNextInt() instead of catching every bad input when you can).

Summary#

  • try the risky code, catch specific exceptions, use finally (or try-with-resources) for clean-up.
  • Checked exceptions must be caught or declared with throws; unchecked ones (RuntimeException) are usually bugs.
  • throw new X("message") raises an exception; create custom exceptions by extending Exception or RuntimeException.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Safe integer parsing

Read lines until the input ends. For each line print <n> squared = <n*n>, or Skipping 'abc': not a number if Integer.parseInt throws NumberFormatException. Finally print Valid numbers: 3.

Test input:
12
abc
7
4.5
30
Expected output:
12 squared = 144
Skipping 'abc': not a number
7 squared = 49
Skipping '4.5': not a number
30 squared = 900
Valid numbers: 3
2

Custom exception for age

Create class InvalidAgeException extends Exception. Write static void register(String name, int age) throws InvalidAgeException that throws it with the message Age 15 is below 18 when age < 18, else prints Registered Asha. The given main must print:

Registered Asha
Error: Age 15 is below 18
Registered Dev
Expected output:
Registered Asha
Error: Age 15 is below 18
Registered Dev

Quick Quiz

Q1.

Which block always runs, whether an exception occurs or not?

Q2.

Which exception is checked (must be handled or declared)?

Q3.

What is the difference between throw and throws?

Q4.

What does try-with-resources do?

Q5.

In multiple catch blocks, which order is correct?