Reading history

Python Exception Handling: try, except, else, finally

4 min read 2 views

Learn Python exception handling: try and except, handling several errors, else and finally, raise, custom exceptions and common built-in errors.

When a line of code cannot do its job while the program runs (the file it opens is missing, the text it converts is not a number, the divisor is zero) Python raises an exception. Left alone, an exception stops the program and prints a traceback. With try and except you can catch it, respond sensibly and carry on. This lesson covers try, except, else, finally, raise and custom exceptions.

In this lesson you will learn

  • How try/except catches errors
  • How to handle different errors differently
  • What the else and finally blocks are for
  • How to raise your own errors
  • How to define a custom exception class

try, except, else and finally

values = ["42", "abc", "0"]

for text in values:
    try:
        number = int(text)
        result = 100 / number
    except ValueError:
        print(f"'{text}' is not a number")
    except ZeroDivisionError:
        print("Cannot divide by zero")
    else:
        print(f"100 / {number} = {result}")
    finally:
        print("-- done with", text)

Output

100 / 42 = 2.380952380952381
-- done with 42
'abc' is not a number
-- done with abc
Cannot divide by zero
-- done with 0
  • Code that might fail goes in try.
  • Each except names the error type it handles. int("abc") raises ValueError; dividing by zero raises ZeroDivisionError.
  • else runs only when the try block raised nothing, which keeps the “success” code apart from the risky code.
  • finally runs every time, error or not. It is the place for clean-up such as closing connections.

Raising Errors and Custom Exceptions

class InsufficientFunds(Exception):
    pass

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError("amount must be positive")
    if amount > balance:
        raise InsufficientFunds(f"need {amount - balance} more")
    return balance - amount

for amt in (300, -5, 900):
    try:
        print("New balance:", withdraw(500, amt))
    except (ValueError, InsufficientFunds) as e:
        print(type(e).__name__ + ":", e)

Output

New balance: 200
ValueError: amount must be positive
InsufficientFunds: need 400 more
  • raise ValueError("message") signals a problem from your own code. The caller decides how to handle it.
  • Custom exceptions are classes that inherit from Exception. A clear name such as InsufficientFunds makes the error self-explaining.
  • except (A, B) as e catches either type and stores the error object in e, whose text is the message you passed to raise.

Common Built-in Exceptions

ExceptionTypical cause
ValueErrorRight type, wrong value: int("abc")
TypeErrorWrong type: "5" + 5
KeyErrorMissing dictionary key
IndexErrorList index out of range
ZeroDivisionErrorDividing by zero
FileNotFoundErrorOpening a file that does not exist
AttributeErrorUsing a method the object does not have

Common Mistakes

  1. A bare except:. It catches everything, including typing mistakes in your own code and Ctrl+C. Name the exceptions you expect.
  2. Putting too much code in try. Wrap only the line that can fail, so other bugs are not hidden.
  3. Silencing errors with pass. At least log or print what happened.
  4. Using exceptions for normal checks. if key in d: is clearer than catching KeyError for simple cases.

Practice Exercises

Exercise 1. Write safe_int(text) that returns the integer, or None when the text is not a number.

Show answer
def safe_int(text):
    try:
        return int(text)
    except ValueError:
        return None

print(safe_int("12"), safe_int("x"))   # 12 None

Exercise 2. Make set_age(n) raise ValueError when n is negative.

Show answer
def set_age(n):
    if n < 0:
        raise ValueError("age cannot be negative")
    return n

Frequently Asked Questions

What is the difference between an error and an exception?

Syntax errors stop Python before the program runs. Exceptions happen while it runs and can be caught with try/except.

Does finally run if I return inside try?

Yes. finally runs before the function actually returns, which is why it is reliable for clean-up.

How do I see the full error while still handling it?

Use the traceback or logging module, for example logging.exception("failed") inside the except block.

Summary

  • try holds risky code and except handles named errors.
  • else runs on success and finally runs every time.
  • raise signals errors; subclass Exception for custom ones.
  • Catch specific exceptions, never everything.

Next: Python File Handling.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *