0
0
PythonHow-ToBeginner · 3 min read

How to Use else with try except in Python: Simple Guide

In Python, you can use an else block after try and except to run code only if no exceptions were raised in the try block. The else block helps separate normal code from error handling.
📐

Syntax

The try-except-else structure has these parts:

  • try: Code that might cause an error.
  • except: Code that runs if an error happens in try.
  • else: Code that runs only if no error happened in try.
python
try:
    # code that might raise an exception
except SomeError:
    # code to handle the exception
else:
    # code to run if no exception occurred
💻

Example

This example shows how else runs only when no error occurs in the try block. If an error happens, the except block runs instead.

python
try:
    number = int(input('Enter a number: '))
except ValueError:
    print('That is not a valid number.')
else:
    print(f'You entered the number {number}.')
Output
Enter a number: 5 You entered the number 5.
⚠️

Common Pitfalls

One common mistake is putting code that might raise exceptions inside the else block. The else block should only contain code that runs if no exceptions happened in try. Also, forgetting the else block when you want to separate normal code from error handling can make your code less clear.

python
try:
    value = int('abc')  # raises ValueError
except ValueError:
    print('Error caught')
else:
    # This code won't run because exception happened
    print('No error')

# Wrong: risky code inside else
try:
    print('Trying')
except Exception:
    print('Error')
else:
    risky_operation()  # If this raises error, it won't be caught here
Output
Error caught Trying
📊

Quick Reference

Use else after except to run code only when no exceptions occur in try. Keep risky code inside try, not else.

PartPurpose
tryRun code that might cause an error
exceptHandle errors raised in try
elseRun code if no errors happened in try

Key Takeaways

Use else after except to run code only if try block succeeds without errors.
Put all code that might raise exceptions inside try, not else.
Else helps keep normal code separate from error handling.
If an exception occurs, else block is skipped.
Else block is optional but useful for clarity.