Posted by Kosal
Handling exceptions in Python is essential for writing robust and reliable code. You can handle exceptions using the try
, except
, else
, and finally
blocks. Here's a basic structure:
try:
# Code block where an exception might occur
# Example: division by zero
result = 10 / 0
except ExceptionType:
# Code block to handle the exception
# Example: division by zero exception
print("An error occurred")
else:
# Code block that executes if no exception occurs
# Example: no exception occurred
print("No error occurred")
finally:
# Code block that always executes, regardless of whether an exception occurred
# Example: cleanup or resource release
print("Finally block executed")
Here's a breakdown of each block:
try
: This block contains the code that might raise an exception.except
: This block catches and handles the exception. You can specify which type of exception to catch (or catch all exceptions using Exception
), or you can omit the exception type to catch all exceptions.else
(optional): This block executes if no exceptions occur in the try
block.finally
(optional): This block always executes, regardless of whether an exception occurred. It's typically used for cleanup or releasing resources.Here's a simple example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful")
finally:
print("Cleanup")
Output:
Cannot divide by zero
Cleanup
Remember, it's essential to handle exceptions gracefully to prevent unexpected crashes and improve the reliability of your code.