Exception Handling in Python
An exception is an error that happens while the program is running, such as dividing by zero or converting text that is not a number. Without handling, the program stops. With try and except you can catch the error and show a friendly message instead.
try: the code that might failexcept: runs when an error happenselse: runs when NO error happensfinally: always runs (clean-up)raise: throw your own exception
Basic Exception Handling
a = 10
b = 0
try:
c = a / b
print(f"c = {c}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Handling Different Exceptions
Use a separate except block for each kind of error.
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ValueError:
print("Error: Please enter a valid number.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Catching Multiple Exceptions Together
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except (ValueError, ZeroDivisionError) as e:
print(f"Error: {e}")
Using the Exception Base Class
Exception catches almost every error. Use it as a last safety net, after the specific exceptions.
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except Exception as e:
print(f"Something went wrong: {e}")
else and finally
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
else:
print(f"Result: {result}") # only when there was no error
finally:
print("Execution completed.") # always runs
Raising Your Own Exception
Use raise to stop the program when data breaks a business rule.
age = 15
if age < 18:
raise Exception("Age must be at least 18 to vote.")
print("You are eligible to vote.")
Example: attendance check
attendance = int(input("Enter your attendance percent: "))
if attendance < 75:
raise Exception("Students with attendance below 75% are not eligible")
print("Congrats, you are eligible!")