Exception Handling in Python
Exceptions are the run time errors. Here is the detail concept related to exception handling in python
Purpose:
The main purpose of handling exception in python are:
Key Concepts:
Following are the key concepts and keywords used to handle runtime errors in python programming:
Common Exceptions:
Following are the most commonly occurring runtime errors:
Best Practices:
Following are the best practices one need to follow while handling exception in program:
Key Concepts in Python Exception Handling:
1. try block:
Example:
value = input("Enter a number: ")
try:
number = int(value)
except ValueError:
print("Invalid input: Please enter a number.")
Output:
Enter a number: aa
Invalid input: Please enter a number.
Explanation: The try block attempts to convert the user's input (value) to an integer (number).
2. except block:
Example :
value = input("Enter a number: ")
try:
number = int(value)
except ValueError:
print("Invalid input: Please enter a number.")
except: # General exception handler (use with caution)
print("An unexpected error occurred.")
Output:
Enter a number: abcd
Invalid input: Please enter a number.
Explanation: The first except handles ValueError for invalid input. The second except (use cautiously) catches other unexpected exceptions.
3. else block:
Example :
value = input("Enter a number: ")
try:
number = int(value)
except ValueError:
print("An unexpected error occurred.")
else:
print("You entered:", number)
Output:
Enter a number: 10
You entered: 10
Explanation: The else block prints the converted number if no exceptions occur.
4. finally block:
Example:
try:
# Code that may raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero!")
finally:
# Code that should be executed regardless of whether an exception occurred
print("This will always execute, regardless of exceptions.")
Output:
Error: Division by zero!
This will always execute, regardless of exceptions.
Explanation: The finally block ensures cleanup happens even if there are errors.
Raising Exceptions:
Example:
try:
# Code that may raise an exception
x = int(input("Enter a number greater than 10: "))
if x <= 10:
raise ValueError("Number must be greater than 10")
except ValueError as ve:
print("Error:", ve)
finally:
# Code that should be executed regardless of whether an exception occurred
print("This will always execute, regardless of exceptions.")
Output:
Enter a number greater than 10: 7
Error: Number must be greater than 10
This will always execute, regardless of exceptions.