How does exception handling work in Python?
Python handles errors with the try and except blocks. The risky code goes in try, and if an error happens, the matching except block runs instead of the program crashing.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(result)
finally:
print("Done")
Output:
Tutorials Class - Output Window
Cannot divide by zero
Done
try: the code that may raise an error.except: runs if that error happens. You can have more than one.else: runs only if no error happened.finally: always runs, good for cleanup like closing a file.
Catch the specific error you expect, not every error. You can also raise your own error with raise. See Python Errors.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |