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

Introduction to the try Statement

in Python
• Presented by: [Your Name]
• Date: [Today's Date]
Agenda
• 1. Introduction to Exceptions
• 2. The try Statement
• 3. except Block
• 4. else and finally Blocks
• 5. Common Use Cases
• 6. Summary
• 7. Q&A
What are Exceptions?
• Errors that occur during program execution
• Examples: Division by zero, file not found,
invalid input
The try Statement
• Used to catch and handle exceptions
• Syntax:
• try:
• # code that may cause an exception
• except ExceptionType:
• # code that runs if exception occurs
The except Block
• Catches specific or general exceptions
• Syntax:
• except ExceptionType:
• # handle the exception
• Example:
• try:
• x=1/0
• except ZeroDivisionError:
• print('Cannot divide by zero')
Multiple except Blocks
• Handle different exceptions differently
• Syntax:
• try:
• # code that may cause an exception
• except TypeError:
• # handle TypeError
• except ValueError:
• # handle ValueError
The else Block
• Runs if no exception occurs
• Syntax:
• try:
• # code that may cause an exception
• except ExceptionType:
• # handle the exception
• else:
• # code that runs if no exception occurs
The finally Block
• Runs no matter what (exception or not)
• Syntax:
• try:
• # code that may cause an exception
• except ExceptionType:
• # handle the exception
• else:
• # code that runs if no exception occurs
• finally:
Common Use Cases
• File operations
• User input validation
• Network operations
Example: File Operations
• try:
• file = open('example.txt', 'r')
• content = file.read()
• except FileNotFoundError:
• print('File not found')
• finally:
• file.close()
Summary
• try and except for handling exceptions
• else for code that runs if no exception
• finally for cleanup actions
Q&A and MCQ
• Question 1: What is the purpose of the try
block?
• a) To handle exceptions
• b) To execute code that may cause an
exception
• c) To clean up resources
• d) None of the above

• Question 2: Which block runs if no exception

You might also like