The except
statement in Python is a part of the try-except
block, which is used to handle exceptions and errors gracefully. It allows you to catch and respond to specific or general exceptions, ensuring that your program doesn’t crash when an error occurs.
Example
try:
num = int("abc") # This raises a ValueError
except ValueError:
print("Invalid input, please enter a number.")
Output:
Invalid input, please enter a number.
Syntax
try:
# Code block that might raise an exception
except ExceptionType:
# Code to handle the exception
- try block: Contains the code that may raise an exception.
- except block: Contains the code that executes if an exception occurs.
- ExceptionType (optional): Specifies the type of exception to catch. If omitted, it catches all exceptions.
Why Use except?
The except
statement is essential for making your code robust and user-friendly by handling unexpected errors without stopping program execution. It allows developers to log errors, provide meaningful messages, or recover from failures. Lets see some example:
1. Handling Specific Exceptions
Scenario: Catching a specific exception like ValueError
.
try:
num = int("abc")
except ValueError:
print("Please provide a valid number.")
Output:
Please provide a valid number.
2. Catching Multiple Exceptions
Scenario: Handling multiple types of exceptions.
try:
num = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input.")
Output:
Cannot divide by zero.
3. Catching All Exceptions
Scenario: Handling any unexpected exception.
try:
result = 10 / "a"
except Exception as e:
print(f"An error occurred: {e}")
Output:
An error occurred: unsupported operand type(s) for /: 'int' and 'str'
4. Using else with except
Scenario: Run code only if no exception occurs.
try:
num = int("123")
except ValueError:
print("Invalid number.")
else:
print(f"Conversion successful: {num}")
Output:
Conversion successful: 123
5. Using finally with except
Scenario: Run cleanup code regardless of whether an exception occurs.
try:
num = int("abc")
except ValueError:
print("Invalid number.")
finally:
print("Execution complete.")
Output:
Invalid number.
Execution complete.