Exception Handling
Exception Handling
Built-in Exceptions
Python provides several built-in exceptions to handle common errors:
Examples:
1. ZeroDivisionError:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
2. ValueError:
try:
number = int("abc")
except ValueError:
print("Invalid input; please enter a number.")
3. IndexError:
my_list = [1, 2, 3]
try:
print(my_list[5])
except IndexError:
print("Index out of range.")
Raising Exceptions
You can raise exceptions manually using the raise keyword to indicate an error condition.
Example:
1. Raising a ValueError:
def check_positive(number):
if number < 0:
raise ValueError("Negative numbers are not allowed!")
return number
try:
print(check_positive(-5))
except ValueError as e:
print(e)
2. Raising a TypeError:
def add_numbers(a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("Both arguments must be integers.")
return a + b
try:
print(add_numbers(5, "10"))
except TypeError as e:
print(e)
class CustomError(Exception):
pass
def trigger_error():
raise CustomError("This is a custom error.")
try:
trigger_error()
except CustomError as e:
print(e)
Handling Exceptions
Use a try-except block to handle exceptions and prevent program crashes.
Example:
1. Handling ZeroDivisionError:
try:
result = 10 / 0
except ZeroDivisionError:
print("Oops! You can't divide by zero.")
3. Handling TypeError:
try:
result = "string" + 10
except TypeError:
print("Cannot add a string and an integer.")
Finally Clause
The finally clause is a block of code that always executes, regardless of whether an exception
occurred.
Example:
1. File Handling:
try:
file = open("example.txt", "r")
except FileNotFoundError:
print("File not found!")
finally:
file.close()
print("File closed.")
2. Database Connection:
try:
connection = connect_to_database()
except ConnectionError:
print("Failed to connect to database.")
finally:
connection.close()
print("Connection closed.")
3. Resource Cleanup:
try:
resource = acquire_resource()
except ResourceError:
print("Resource acquisition failed.")
finally:
release_resource(resource)
print("Resource released.")
Sample Solution:
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 / num2
print(f"The result is: {result}")
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
except ValueError:
print("Error: Please enter valid numbers.")
finally:
print("Program execution completed.")
Conclusion
Exception handling is essential for writing robust programs. By using try-except blocks,
raising exceptions, and utilizing the finally clause, you can manage unexpected situations
effectively and prevent program crashes. Keep practicing to master exception handling!