15_Exception Handling
15_Exception Handling
Learning objective
• What is exception handling?
• Try and Except block/Statement - Catching Exceptions
• else and finally block
• How to Raise an Exception
What is exception handling?
• Mechanism to handle runtime errors that may occur during program
execution .
• if we try to access the index from the list, which is more than the
list’s length, exception is raised and handled during the program
execution.
else block
• In Python's exception handling, the else and finally blocks serve
specific purposes in addition to the try and except blocks.
• else Block:
• The else block is optional and follows the try and except blocks.
• It contains code that will be executed if no exceptions are raised in
the corresponding try block.
• If no exception occurs, the code inside the else block is executed.
• If an exception occurs and is caught by an except block, the else
block is skipped.
else block
• In Python's exception handling, You can define as many exception blocks as
you want, e.g. if you want to execute a special block of code for a special kind
of error:
num1 = 10
num2 = 2
try:
# Code that may cause an exception
result = num1 / num2
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
else:
print("Result:", result)
finally block
• finally block:
• The finally block is optional and follows the try and except (and
optionally else) blocks.
# Valid division
result1=divide(10, 2)
print("Result 1:", result1)
# Attempt to divide by zero (raising an exception)
try:
result2 = divide(8, 0)
print("Result 2:", result2)
except ZeroDivisionError as ZDE:
print("Error:", ZDE)
def check_positive(number):
# Raise an exception if the number is not positive
if number <= 0:
raise ValueError("Number must be positive.")
print(f"{number} is a positive number.")
try:
user_number = float(input("Enter a positive number: "))
check_positive(user_number)
print("Program complete.")
def check_age(age):
# Raise an exception if the age is less than 20 or greater than 50
if age < 20 or age > 50:
raise ValueError("Age must be between 20 and 50.")
print(f"Age {age} is valid.")
try:
# Get age input from the user
user_age = int(input("Enter your age: "))
check_age(user_age)