JV
PY

Java to Python

10 lessons

Progress0%
1Variables & Types2Classes & OOP3Collections4Exception Handling5File I/O6Functional Programming7Duck Typing and Protocols8Python Ecosystem9Type Hints and Static Analysis10Context Managers and Resources
All Mirror Courses
JV
PY
Exception Handling
MirrorLesson 4 of 10
Lesson 4

Exception Handling

Error handling patterns

Introduction

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

Mirror Card
JV
From Java:

In Java, you're familiar with error handling patterns.

PY
In Python:

Python has its own approach to error handling patterns, which we'll explore step by step.

The Python Way

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

PY
Python Example
# All exceptions are unchecked in Python
class NotFoundException(Exception):
    def __init__(self, message: str):
        super().__init__(message)

def find_user(user_id: int):
    if user_id not in users:
        raise NotFoundException(f"User {user_id} not found")
    return users[user_id]

try:
    u = find_user(42)
except NotFoundException as e:
    print(f"Not found: {e}")
except Exception:
    raise  # bare raise preserves traceback
finally:
    print("done")

Comparing to Java

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

JV
Java (What you know)
// Checked exception
public class NotFoundException extends Exception {
    public NotFoundException(String msg) { super(msg); }
}

// Must declare or catch checked exceptions
public User findUser(int id) throws NotFoundException {
    if (!users.containsKey(id))
        throw new NotFoundException("User " + id + " not found");
    return users.get(id);
}

try {
    User u = findUser(42);
} catch (NotFoundException e) {
    System.out.println("Not found: " + e.getMessage());
} catch (Exception e) {
    throw e;
} finally {
    System.out.println("done");
}
Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

PY
In Python:

Python has no checked exceptions; Java forces you to declare or catch them

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

PY
In Python:

Python 'except Type as e' = Java 'catch (Type e)'

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

PY
In Python:

Python bare 'raise' = Java bare 'throw' to rethrow

Mirror Card
JV
From Java:

You may be used to different syntax or behavior.

PY
In Python:

Python exception hierarchy: BaseException > Exception > specific

Step-by-Step Breakdown

1. No Checked Exceptions

Python has no checked exceptions. All exceptions extend Exception. No throws declaration needed on function signatures.

JV
Java
public void save() throws IOException { ... }
PY
Python
def save():  # no throws needed
    # just raise if something goes wrong

2. except Syntax

Python's except clause is similar to Java's catch, but uses 'as' instead of the exception type before the variable.

JV
Java
catch (NotFoundException e) { e.getMessage() }
PY
Python
except NotFoundException as e: str(e)

3. Bare raise

Bare 'raise' in Python rethrows the current exception preserving the original traceback, like Java's bare 'throw'.

JV
Java
throw; // Java bare rethrow
PY
Python
raise   # Python bare rethrow

Common Mistakes

When coming from Java, developers often make these mistakes:

  • Python has no checked exceptions; Java forces you to declare or catch them
  • Python 'except Type as e' = Java 'catch (Type e)'
  • Python bare 'raise' = Java bare 'throw' to rethrow
Common Pitfall
Don't assume Python works exactly like Java. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • Python has no checked exceptions
  • except Type as e = catch (Type e)
  • Bare raise = bare throw (preserves traceback)
  • finally works identically
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your Java code in Python to practice these concepts.
PreviousNext