Python 24-Day Course Day 12 python intermediate
Python 24-Day Course - Day 12: Exception Handling 2026-03-14 · 2 min read
Day 12: Exception Handling
Basic Exception Handling
try :
number = int ( input ( "Enter a number: " ))
result = 100 / number
print ( f "Result: { result } " )
except ValueError :
print ( "Please enter a valid number" )
except ZeroDivisionError :
print ( "Cannot divide by zero" )
try-except-else-finally
try :
f = open ( "data.txt" , "r" )
content = f.read()
except FileNotFoundError :
print ( "File not found" )
else :
print ( f "File content: { content } " ) # Runs only if no error
finally :
print ( "Operation complete" ) # Always runs
Common Built-in Exceptions
Exception When It Occurs ValueErrorInvalid value conversion TypeErrorInvalid type operation KeyErrorDictionary key not found IndexErrorIndex out of range FileNotFoundErrorFile not found ZeroDivisionErrorDivision by zero AttributeErrorAccessing non-existent attribute
Custom Exceptions
class InsufficientBalanceError ( Exception ):
def __init__ (self, balance, amount):
self .balance = balance
self .amount = amount
super (). __init__ (
f "Insufficient balance: balance { balance } , withdrawal request { amount } "
)
def withdraw (balance, amount):
if amount > balance:
raise InsufficientBalanceError(balance, amount)
return balance - amount
try :
result = withdraw( 1000 , 5000 )
except InsufficientBalanceError as e:
print (e) # Insufficient balance: balance 1000, withdrawal request 5000
Today’s Exercises
Create a function that validates user input to accept only integers between 1 and 100.
Write a safe file reading function that handles all possible exceptions.
Create a NegativeNumberError custom exception and use it in practice.
← Previous Day 11: Day 11: File I/O Next → Day 13: Day 13: Class Basics Was this article helpful?
Thanks for your feedback!