0% found this document useful (0 votes)
3 views

15_Exception Handling

The document explains exception handling in Python, detailing the use of try and except blocks to catch and manage runtime errors, as well as the roles of else and finally blocks. It also covers how to raise exceptions intentionally to indicate errors or exceptional conditions in code. Overall, it emphasizes the importance of handling exceptions to prevent program crashes and provide user-friendly feedback.

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

15_Exception Handling

The document explains exception handling in Python, detailing the use of try and except blocks to catch and manage runtime errors, as well as the roles of else and finally blocks. It also covers how to raise exceptions intentionally to indicate errors or exceptional conditions in code. Overall, it emphasizes the importance of handling exceptions to prevent program crashes and provide user-friendly feedback.

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Exception handling in Python

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 .

• Gracefully handle errors, preventing the program from crashing.

• Provides meaningful feedback to the user.

• When a Python code comes across a condition it can't handle, it


raises an exception. An object that describes an error is called an
exception.
try and except Statement
• In Python, we catch exceptions and handle them using try and
except code blocks.

• try: The block of code where you anticipate an exception.

• except: The block of code that will be executed if an exception


occurs inside the corresponding try block.
try and except Statement
a = ["Python", "Exceptions", "try and except"]
try:
for i in range(4):
print("The index and element from the list is", i, a[i])
except:
print("Index out of range")

• 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.

• It contains code that will be executed whether an exception


occurs or not.

• It is typically used for cleanup operations that must be performed,


regardless of whether an exception occurred.
Try, except, else and finally blocks
num1 = 15
num2 = 20
try:
# Code that may cause an exception
result = num1 / num2
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
else:
print("Result:", result)
finally:
print("This will be executed no matter what.")
In summary
• Try Block: Contains the code that might cause an exception.
• Except Block: Catch specific or general exceptions.
• Else block: Executes only if no exceptions are raised.
• Finally Block: Executes regardless of whether an exception was
raised, often used for clean up tasks

• This way, the program won’t crash due to an unhandled exception,


and the user will get a friendly message if something goes wrong.
How to raise an exception
• In Python, you can raise exceptions to indicate that an error or
exceptional condition has occurred in your code.

• This can be useful when you want to handle errors in a specific


way or when you want to propagate the error to higher levels of
your program.

• You can raise an exception using the raise statement.


def divide(x, y):
if y == 0:
raise ZeroDivisionError("Cannot divide by zero")
return x / y

# 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)

# Catch the ValueError raised in the function


except ValueError as e:
print(f"Error: {e}")

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)

# Catch the ValueError raised in the function


except ValueError as e:
print(f"Invalid input: {e}")

# Finally block to signify end of program


finally:
print("Age check complete.")
You must have learnt:
• What is exception handling?
• Try and Except block/Statement - Catching Exceptions
• else and finally block
• How to Raise an Exception

You might also like