Back
+10 XP
Concept

The `else` Block in Exception Handling

Code inside `else:` runs only if NO exceptions were raised in the `try:` block. This keeps your `try` block small and focused.

python
try:
    val = int("42")
except ValueError:
    print("Invalid number")
else:
    print(f"Success! Parsed: {val}")

# 111. The `else` Block in Exception Handling Code inside `else:` runs only if NO exceptions were raised in the `try:` block. This keeps your `try` block small and focused: ```python try: val = int("42") except ValueError: print("Invalid number") else: print(f"Success! Parsed: {val}") ``` Best practice: Keep only the single dangerous line of code inside `try:`. Place code that relies on that operation succeeding inside `else:`. This avoids accidentally catching unexpected errors from secondary logic.

Checkpoint

When does the `else` block execute in a `try/except/else` structure?

Practice

Convert `"100"` with `int()` in a `try` block. In the `else:` block, print `"Parsed successfully"`. Add an `except ValueError:` as well.

Terminal
01
Tap code blocks below to assemble
Available Blocks