Handling Exceptions with try and except
The try...except statement allows you to handle errors that may occur during program execution without crashing the program.
It helps maintain stability and ensures a smoother user experience by safely managing unexpected issues.
Using the try...except Statement
Code that might cause an exception is placed inside a try block. If an error occurs, the program jumps to the corresponding except block to handle it.
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero.")
In the example above, 10 / 0 raises a ZeroDivisionError, an exception that occurs when dividing a number by zero. This exception is handled by the except block, allowing the program to continue running without interruption.
Handling Various Exceptions
You can use multiple except blocks to handle different types of exceptions. Each block corresponds to a specific type of exception.
try: # Code that may raise different types of exceptions ... except ZeroDivisionError: print("Cannot divide by zero.") except ValueError: print("Invalid input.") except Exception as e: print(f"An unexpected error occurred: {e}")
Lessons in this chapter · Data Types in Pythons
- 1. Data Types Representing Kinds of Data
- 2. How to Represent Text, Numbers, and True/False in Python
- 3. How to Check Variable and Value Types
- 4. What to Watch Out for When Creating String Data?
- 5. Understanding and Using Escape Characters
- 6. How to Create Multiline Strings?
- 7. Multiple-choice quiz
- 8. Concatenating Strings with the `+` Operator
- 9. Using the (*) Operator for String Repetition
- 10. Selecting Specific Parts of a String Using Indexing
- 11. How to Select Specific Ranges from a String
- 12. Handling Exceptions with try and except
- 13. String IndexError(index out of range) Exception
- 14. Python String Indexing Coding Quiz
- 15. Multiple-choice quiz
- 16. Fill-in-the-blank quiz
In a try...except statement, which block is used to handle a specific exception when it occurs?
try block
finally block
except block
else block
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help