20 exception handling programs: catching specific errors, else and finally, raising and re-raising, custom exceptions, retries and safe input parsing. Each solution runs both the success path and the failure path so you can see every branch.
Write a Python program showing why specific exceptions must be caught before general ones.
Output
True True
specific handler: file not found
Approach
FileNotFoundError is a subclass of OSError, so it must come first.
Solution
Python
print(issubclass(FileNotFoundError,OSError),issubclass(OSError,Exception))try:open("nope.txt")exceptFileNotFoundError:print("specific handler: file not found")exceptOSError:print("general handler: some OS error")
Output
True True
specific handler: file not found
Line by line
Line 1
Python checks except blocks top to bottom and uses the first that matches, so a general OSError first would hide the specific one.
Learn the concept
New to this topic? Read the lesson, then come back.
Write a Python program that validates several fields and reports every error at once.
Output
valid
3 errors: name is required; email is invalid; age must be 18-120
Approach
Collect messages in a list and raise one exception at the end.
Solution
Python
classValidationError(Exception):def__init__(self,errors):super().__init__("; ".join(errors))self.errors=errorsdefvalidate(user):errors=[]ifnotuser.get("name"):errors.append("name is required")if"@"notinuser.get("email",""):errors.append("email is invalid")ifnot18<=user.get("age",0)<=120:errors.append("age must be 18-120")iferrors:raiseValidationError(errors)return"valid"foruserin[{"name":"Asha","email":"asha@x.com","age":29},{"name":"","email":"bad","age":5}]:try:print(validate(user))exceptValidationErrorase:print(len(e.errors),"errors:",e)
Output
valid
3 errors: name is required; email is invalid; age must be 18-120
Line by line
Lines 7-14
Every check runs, so the user sees all problems at once instead of one at a time.
Learn the concept
New to this topic? Read the lesson, then come back.