ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Python Tutorial• 7 min read

Exception Handling: try, except, else & finally

Graceful error recovery, specific exceptions, and custom Exception classes

Errors happen. Robust software anticipates failure using try...except...else...finally blocks to handle network timeouts, invalid inputs, and missing files gracefully.

The Full Exception Handling Block

try: Code that might raise an exception.

except SpecificError as e: Catches only matching error types (never use a bare except:, which catches keyboard interrupts!).

else: Runs ONLY if NO exception was raised in the try block.

finally: Always executes regardless of whether an error was raised or caught (ideal for closing database connections).

Production Exception Architecture
class ValidationError(Exception):
    """Custom domain exception."""
    pass

def process_age(age_str):
    try:
        age = int(age_str)
        if age < 0 or age > 130:
            raise ValidationError(f"Invalid human age: {age}")
    except ValueError:
        print("Error: Input could not be parsed as an integer.")
        return None
    except ValidationError as err:
        print(f"Validation failure: {err}")
        return None
    else:
        print(f"Age {age} verified successfully!")
        return age
    finally:
        print("Audit: Verification routine completed.")
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which block in a `try...except...else...finally` statement executes ONLY if no exception occurred?