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
- Write a function
divide(a, b)that converts both values to integers and divides them insidetry. CatchZeroDivisionErrorandValueErrorin separateexceptblocks, print the result inelse, and print a message infinally. - Call
dividewith good values, with 0 as the divisor, and with text that is not a number. - In separate
tryblocks, cause and catch anIndexError(list index too large), aKeyError(missing dictionary key), aFileNotFoundError(opening a file that does not exist) and aTypeError(adding a string and a number). - Catch two kinds of exceptions in one
exceptby giving a tuple of exception types. - Write a function
check_age(age)that usesraise ValueError(...)when the age is negative, and catch that exception. - Catch any other error with
except Exception as eand print its type and message. - Print a final message to show the program finished without crashing.
Program
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
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 normallyRecorded 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:
tryholds the code that may fail.except SomeErrorruns only if that kind of error happens insidetry. Python checks theexceptblocks from top to bottom and runs the first one that matches.elseruns only iftryfinished with no error.finallyruns 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 Exceptionbefore more specific blocks such asexcept 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 anexceptblock meant for something else, giving a wrong message. Keep only the risky line intry, and put code that should run only on success inelse.Thinking
finallyruns 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
tryfinishes without raising an exception.When does the finally block run?
Always: after
trysucceeds, after anexceptblock 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 withtryandexcept.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:.