JS
PY

JavaScript to Python

10 lessons

Progress0%
1Variables and Constants2Functions3Arrays vs Lists4Objects vs Dictionaries5Classes and OOP6Modules and Imports7Array Methods vs Comprehensions8Error Handling9Async Programming10File I/O
All Mirror Courses
JS
PY
Error Handling
MirrorLesson 8 of 10
Lesson 8

Error Handling

Catching and throwing exceptions

Introduction

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

Mirror Card
JS
From JavaScript:

In JavaScript, you're familiar with catching and throwing exceptions.

PY
In Python:

Python has its own approach to catching and throwing exceptions, 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
import json

# try / except / else / finally
try:
    data = json.loads(bad_json)
except json.JSONDecodeError as e:
    print(f"Bad JSON: {e}")
except Exception as e:
    raise          # re-raise the same exception
else:
    print("Parsed OK:", data)  # runs if no exception
finally:
    print("Always runs")

# Custom exception
class ValidationError(Exception):
    def __init__(self, field, msg):
        super().__init__(msg)
        self.field = field

raise ValidationError("email", "Invalid email")

Comparing to JavaScript

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

JS
JavaScript (What you know)
// try / catch / finally
try {
  const data = JSON.parse(badJson);
} catch (err) {
  if (err instanceof SyntaxError) {
    console.error("Bad JSON:", err.message);
  } else {
    throw err; // re-throw unknown errors
  }
} finally {
  console.log("Always runs");
}

// Custom error
class ValidationError extends Error {
  constructor(field, msg) {
    super(msg);
    this.name = "ValidationError";
    this.field = field;
  }
}

throw new ValidationError("email", "Invalid email");
Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

except instead of catch, multiple except blocks allowed

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

else block runs when no exception occurred

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

raise (no argument) re-raises the current exception

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

Exceptions inherit from Exception, not Error

Step-by-Step Breakdown

1. Basic try/except

Python allows multiple except blocks for different error types.

JS
JavaScript
try { ... } catch (err) { ... }
PY
Python
try:
    ...
except ValueError:
    ...
except TypeError:
    ...

2. The else Block

The else block only runs when no exception was raised — useful for code that should only run on success.

JS
JavaScript
// No direct equivalent — must use a flag
PY
Python
try:
    result = do_thing()
except SomeError:
    handle()
else:
    use(result)  # only if no error
Rule of Thumb
Prefer else over putting success code in the try block — it makes intent clearer.

3. Re-raising Exceptions

bare raise re-raises the current exception preserving its traceback.

JS
JavaScript
throw err; // re-throw with same stack
PY
Python
raise  # re-raise current exception (same traceback)
Common Pitfall
raise e creates a new traceback. Use bare raise to preserve the original.

Common Mistakes

When coming from JavaScript, developers often make these mistakes:

  • except instead of catch, multiple except blocks allowed
  • else block runs when no exception occurred
  • raise (no argument) re-raises the current exception
Common Pitfall
Don't assume Python works exactly like JavaScript. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • except replaces catch, multiple types supported
  • else runs on success, finally always runs
  • bare raise to re-raise without losing traceback
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your JavaScript code in Python to practice these concepts.
PreviousNext