Skip to content
Laviyx Learn

Try

Python Lab · Experiment 27

Exception handling with common built-in exceptions

PythonWeek 5JNTUH R22 · CS206ES

Aim

To write a Python program that shows the full structure of exception handling (try, except, else and finally) and catches the common built-in exceptions: ZeroDivisionError, ValueError, IndexError, KeyError, FileNotFoundError and TypeError, and raises an exception with raise.

Algorithm

  1. Write a function divide(a, b) that converts both values to integers and divides them inside try. Catch ZeroDivisionError and ValueError in separate except blocks, print the result in else, and print a message in finally.
  2. Call divide with good values, with 0 as the divisor, and with text that is not a number.
  3. In separate try blocks, cause and catch an IndexError (list index too large), a KeyError (missing dictionary key), a FileNotFoundError (opening a file that does not exist) and a TypeError (adding a string and a number).
  4. Catch two kinds of exceptions in one except by giving a tuple of exception types.
  5. Write a function check_age(age) that uses raise ValueError(...) when the age is negative, and catch that exception.
  6. Catch any other error with except Exception as e and print its type and message.
  7. Print a final message to show the program finished without crashing.

Program

Python
import math


def divide(a, b):
    print(f"divide({a!r}, {b!r})")
    try:
        result = int(a) / int(b)
    except ZeroDivisionError:
        print("  except: cannot divide by zero")
    except ValueError as e:
        print("  except: not a whole number ->", e)
    else:
        print("  else: result =", result)
    finally:
        print("  finally: this block always runs")


def check_age(age):
    if age < 0:
        raise ValueError("age cannot be negative")
    return age


print("1. try / except / else / finally")
divide("10", "4")
divide("10", "0")
divide("10", "ten")

print("\n2. Other built-in exceptions")
marks = [78, 85, 91]
student = {"name": "Ravi", "branch": "CSE"}

try:
    print(marks[5])
except IndexError as e:
    print("IndexError:", e)

try:
    print(student["pincode"])
except KeyError as e:
    print("KeyError: no key", e)

try:
    with open("missing.txt") as f:
        print(f.read())
except FileNotFoundError as e:
    print("FileNotFoundError:", e)

try:
    print("Total: " + 100)
except TypeError as e:
    print("TypeError:", e)

print("\n3. One except for two exception types")
for value in ["25", "abc", None]:
    try:
        number = int(value)
        print(f"{value!r} converted to {number}")
    except (ValueError, TypeError) as e:
        print(f"{value!r} could not be converted: {type(e).__name__}")

print("\n4. Raising an exception with raise")
for age in [20, -5]:
    try:
        check_age(age)
        print("Valid age:", age)
    except ValueError as e:
        print("ValueError raised:", e)

print("\n5. Catching any other exception")
try:
    print(math.sqrt(-1))
except Exception as e:
    print("Error of type", type(e).__name__, "->", e)

print("\nProgram finished normally")

Output

Output
1. try / except / else / finally
divide('10', '4')
  else: result = 2.5
  finally: this block always runs
divide('10', '0')
  except: cannot divide by zero
  finally: this block always runs
divide('10', 'ten')
  except: not a whole number -> invalid literal for int() with base 10: 'ten'
  finally: this block always runs

2. Other built-in exceptions
IndexError: list index out of range
KeyError: no key 'pincode'
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
TypeError: can only concatenate str (not "int") to str

3. One except for two exception types
'25' converted to 25
'abc' could not be converted: ValueError
None could not be converted: TypeError

4. Raising an exception with raise
Valid age: 20
ValueError raised: age cannot be negative

5. Catching any other exception
Error of type ValueError -> math domain error

Program finished normally

Recorded by running this exact program.

How it works

The order of the blocks is always try, then one or more except, then an optional else, then an optional finally:

  • try holds the code that may fail.
  • except SomeError runs only if that kind of error happens inside try. Python checks the except blocks from top to bottom and runs the first one that matches.
  • else runs only if try finished with no error.
  • finally runs in every case, error or not. It is used for clean-up work such as closing files.

except ValueError as e stores the exception object in e; printing e gives Python's message, and type(e).__name__ gives the exception's name. Put specific exceptions first and the general except Exception last; if Exception comes first, it catches everything and the specific blocks below it never run.

math.sqrt(-1) raises a ValueError with the message "math domain error". It is caught by except Exception because every built-in error class is a subclass of Exception.

Common mistakes

  • Writing a bare except: with no exception type. It hides every error, even typing mistakes like a misspelt variable name, so bugs become hard to find. Catch the specific exceptions you expect.

  • Putting except Exception before more specific blocks such as except ZeroDivisionError. The general block matches first and the specific ones never run.

  • Putting all the follow-up code inside try. An error in that code may then be caught by an except block meant for something else, giving a wrong message. Keep only the risky line in try, and put code that should run only on success in else.

  • Thinking finally runs only when there is an error. It runs every time, whether or not an exception happened.

Viva questions

Try to answer each one aloud before you open it.

  • What is an exception?

    An exception is an error that happens while the program is running, such as dividing by zero or opening a missing file. If it is not handled, the program stops and prints a traceback.

  • When does the else block of a try statement run?

    Only when the code inside try finishes without raising an exception.

  • When does the finally block run?

    Always: after try succeeds, after an except block handles an error, and even when an error is not caught. It is used for clean-up such as closing files or connections.

  • What is the difference between a syntax error and an exception?

    A syntax error is found before the program runs, when Python reads the code, and cannot be handled with try. An exception happens while the code is running and can be caught with try and except.

  • What does the raise statement do?

    It creates an exception on purpose, for example raise ValueError("age cannot be negative"), so that the caller can handle the wrong input.

  • How do you catch more than one exception in one except block?

    Give a tuple of exception types: except (ValueError, TypeError) as e:.

Learn the concepts

All Python Programming Lab experiments →