Exception Handling in Python: try, except, else, finally (With Examples)

Exception Handling in Python – try, except, else and finally

Quick answer: Exception handling in Python lets a program respond to runtime errors instead of crashing. Code that might fail goes in a try block; matching errors are handled in except; else runs only when no error occurs; and finally always runs, usually for clean-up. You can also raise exceptions yourself and define custom exception classes by inheriting from Exception.

All code examples were run on Python 3.13; the outputs shown are real.

Contents

Basic try-except

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Output:

Cannot divide by zero

try, except, else and finally Together

else runs only if no exception occurs; finally runs every time, even after return.

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: division by zero")
        return None
    except TypeError:
        print("Error: numbers only")
        return None
    else:
        print("Division successful")
        return result
    finally:
        print("Done")

print(safe_divide(10, 2))
print(safe_divide(10, 0))

Output:

Division successful
Done
5.0
Error: division by zero
Done
None

Handling Invalid User Input (ValueError)

for text in ["25", "abc"]:
    try:
        n = int(text)
        print("Number:", n)
    except ValueError as e:
        print("Invalid input:", e)

Output:

Number: 25
Invalid input: invalid literal for int() with base 10: 'abc'

Catching Multiple Exceptions

Group exceptions in a tuple to handle them with one block.

data = {"a": 1}
for key in ["a", "b"]:
    try:
        print(10 / data[key])
    except (KeyError, ZeroDivisionError) as e:
        print("Problem:", type(e).__name__)

Output:

10.0
Problem: KeyError

Raising Exceptions with raise

Use raise to stop the program when a value is invalid – here, a simple design check:

def check_stress(stress, allowable):
    if stress > allowable:
        raise ValueError(f"Stress {stress} MPa exceeds allowable {allowable} MPa")
    return "Safe"

print(check_stress(120, 250))
try:
    check_stress(300, 250)
except ValueError as e:
    print("Design error:", e)

Output:

Safe
Design error: Stress 300 MPa exceeds allowable 250 MPa

Custom Exceptions

class InvalidMarksError(Exception):
    pass

def set_marks(m):
    if not 0 <= m <= 100:
        raise InvalidMarksError(f"Marks must be 0-100, got {m}")
    return m

try:
    set_marks(120)
except InvalidMarksError as e:
    print(e)

Output:

Marks must be 0-100, got 120

Common Built-in Exceptions

ExceptionWhen it occurs
ZeroDivisionErrorDividing by zero
ValueErrorRight type, wrong value – int(“abc”)
TypeErrorWrong type – “5” + 5
KeyErrorMissing dictionary key
IndexErrorList index out of range
FileNotFoundErrorOpening a file that does not exist
AttributeErrorObject has no such attribute
NameErrorVariable not defined
ImportError / ModuleNotFoundErrorModule cannot be imported

Best Practices

  • Catch specific exceptions, not a bare except:.
  • Keep the try block small – only the lines that can fail.
  • Use with for files so they close automatically.
  • Give clear error messages that say what went wrong and what is expected.
  • Do not silence errors with pass unless you have a good reason.

Frequently Asked Questions

What is exception handling in Python?

It is a way to catch and handle runtime errors using try, except, else and finally so the program can continue or fail gracefully.

What is the difference between else and finally?

else runs only when the try block raises no exception; finally runs every time, whether an exception occurred or not.

How do I raise an exception in Python?

Use the raise keyword with an exception, for example raise ValueError(“Invalid value”).

How do I create a custom exception?

Define a class that inherits from Exception, for example class InvalidMarksError(Exception): pass, and raise it where needed.

What is the difference between an error and an exception?

Syntax errors are found before the program runs and must be fixed in the code; exceptions happen during execution and can be handled.

Related Python Guides

Learn Python With Guidance

Join our Python course or message us on WhatsApp for doubt-clearing and project support.

Scroll to Top