PY
JV

Python to Java

11 lessons

Progress0%
1Introduction2Variables & Types3Functions to Methods4Lists to Arrays5Dicts to Maps6Classes & OOP7Inheritance8Exception Handling9Modules to Packages10Ecosystem11Modern Java Features
All Mirror Courses
PY
JV
Exception Handling
MirrorLesson 8 of 11
Lesson 8

Exception Handling

Exception Handling

Introduction

In this lesson, you'll learn about exception handling in Java. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.

Mirror Card
PY
From Python:

In Python, you're familiar with exception handling.

JV
In Java:

Java has its own approach to exception handling, which we'll explore step by step.

The Java Way

Let's see how Java handles this concept. Here's a typical example:

JV
Java Example
// try / catch / finally (no else block)
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} catch (IllegalArgumentException | NullPointerException e) {
    System.out.println("Combined catch: " + e.getMessage());
} finally {
    System.out.println("Always runs");
}

// Throw
static void validate(int age) throws IllegalArgumentException {
    if (age < 0) throw new IllegalArgumentException("Age cannot be negative");
}

// Custom exception (checked)
class AppError extends Exception {
    int code;
    public AppError(int code, String msg) {
        super(msg);
        this.code = code;
    }
}

// try-with-resources (auto-close)
try (var reader = new BufferedReader(new FileReader("f.txt"))) {
    String line = reader.readLine();
}

Comparing to Python

Here's how you might have written similar code in Python:

PY
Python (What you know)
# try / except / else / finally
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
except (TypeError, ValueError) as e:
    print(f"Type/Value error: {e}")
else:
    print("No error!")
finally:
    print("Always runs")

# Raise
def validate(age):
    if age < 0:
        raise ValueError("Age cannot be negative")

# Custom exception
class AppError(Exception):
    def __init__(self, code, msg):
        super().__init__(msg)
        self.code = code
Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Python except → Java catch; Python allows multiple except, Java allows multiple catch

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Python has an else block (no exception); Java does not

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Java has checked exceptions that must be declared with throws in the method signature

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Multi-catch in Java uses | to combine exception types

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Java try-with-resources automatically closes AutoCloseable objects

Step-by-Step Breakdown

1. try/catch vs try/except

The structure is nearly identical. except becomes catch, and the exception variable uses parentheses.

PY
Python
try:
    x = 1 / 0
except ZeroDivisionError as e:
    print(e)
JV
Java
try {
    int x = 1 / 0;
} catch (ArithmeticException e) {
    System.out.println(e.getMessage());
}

2. Checked Exceptions

Java's checked exceptions (those extending Exception but not RuntimeException) must be declared in the method signature with throws or caught explicitly.

PY
Python
# Python: no concept of checked exceptions
JV
Java
static void readFile(String path) throws IOException {
    // compiler forces caller to handle IOException
}
Common Pitfall
Ignoring checked exceptions by catching Exception and doing nothing is an anti-pattern. Always handle or re-throw meaningfully.

3. Multi-catch

Java 7+ allows catching multiple exception types in one catch block using |.

PY
Python
except (TypeError, ValueError) as e:
    print(e)
JV
Java
catch (IllegalArgumentException | NullPointerException e) {
    System.out.println(e.getMessage());
}

4. try-with-resources

Java try-with-resources automatically calls .close() on AutoCloseable objects — the equivalent of Python's with statement.

PY
Python
with open("file.txt") as f:
    data = f.read()
JV
Java
try (var reader = new BufferedReader(new FileReader("file.txt"))) {
    String data = reader.readLine();
}

Common Mistakes

When coming from Python, developers often make these mistakes:

  • Python except → Java catch; Python allows multiple except, Java allows multiple catch
  • Python has an else block (no exception); Java does not
  • Java has checked exceptions that must be declared with throws in the method signature
Common Pitfall
Don't assume Java works exactly like Python. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • except → catch, same structure
  • Checked exceptions must be declared with throws or caught
  • try-with-resources ≈ Python with statement
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your Python code in Java to practice these concepts.
PreviousNext