Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 12

Advanced Usage of the try

Statement in Python
• Presented by: [Your Name]
• Date: [Today's Date]
Agenda
• 1. Review of Basic try Statement
• 2. Nested try Statements
• 3. Raising Exceptions
• 4. Custom Exceptions
• 5. Best Practices
• 6. Summary
• 7. Q&A
Review of Basic try Statement
• try, except, else, finally
• Basic usage and syntax
Nested try Statements
• try statements within try statements
• Example:
• try:
• try:
• x=1/0
• except ZeroDivisionError:
• print('Inner exception caught')
• except:
• print('Outer exception caught')
Raising Exceptions
• Use raise to trigger an exception
• Syntax:
• if condition:
• raise ExceptionType('Error message')
Example: Raising Exceptions
• def check_age(age):
• if age < 0:
• raise ValueError('Age cannot be negative')
• return age
• try:
• age = check_age(-1)
• except ValueError as e:
• print(e)
Custom Exceptions
• Define your own exceptions
• Syntax:
• class CustomException(Exception):
• pass
Example: Custom Exceptions
• class NegativeAgeError(Exception):
• def __init__(self, age):
• self.age = age
• super().__init__(f'Age cannot be negative:
{age}')
• def check_age(age):
• if age < 0:
• raise NegativeAgeError(age)
• return age
Best Practices
• Catch specific exceptions
• Use finally for cleanup
• Avoid overusing exceptions for flow control
Example: Best Practices
• try:
• file = open('example.txt', 'r')
• content = file.read()
• except FileNotFoundError:
• print('File not found')
• except IOError:
• print('IO error')
• finally:
• if file:
Summary
• Nested try statements
• Raising exceptions
• Custom exceptions
• Best practices
Q&A and MCQ
• Question 1: How do you trigger an exception
manually?
• a) Using raise
• b) Using try
• c) Using except
• d) Using finally

• Question 2: What is the purpose of custom


exceptions?

You might also like