Handling Exceptions with try and except
The try...except
statement is used to handle exceptions (errors) that may occur during the execution of a program.
Handling exceptions can enhance the stability of a program and protect users and data from unexpected errors.
Using the try...except Statement
You write code that might cause an exception inside the try
block. The code that handles the exception if it occurs is written inside the except
block.
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}")
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
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result