Error Handling and Exceptions
Error handling is an essential aspect of writing robust Python code. Python provides built-in mechanisms to manage errors and exceptions, allowing your program to continue running smoothly or handle unexpected conditions gracefully. This module covers the basics of exception handling, using the try, except, else, and finally blocks, as well as raising and creating custom exceptions.
Subtopic 1: Introduction to Exception Handling
Exception handling allows you to deal with runtime errors, also known as exceptions, that occur during the execution of a program. These errors can occur for various reasons, such as invalid input, missing files, or network problems. Instead of letting your program crash, Python provides a way to catch these errors and handle them gracefully.
What is an Exception?
An exception is an event that disrupts the normal flow of a program's execution. Common exceptions in Python include ZeroDivisionError, FileNotFoundError, TypeError, etc.
Example of an Exception:
try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
In the above example, a ZeroDivisionError occurs when attempting to divide by zero, and it is caught and handled by the except block.
Subtopic 2: Using try, except, else, finally
Python uses the try block to wrap code that might raise an exception, and the except block to handle it. The else block runs if no exception is raised, and the finally block always runs, regardless of whether an exception occurred.
Syntax:
try:
# Code that may raise an exception
except ExceptionType:
# Code that runs if an exception occurs
else:
# Code that runs if no exception occurs
finally:
# Code that always runs
Example:
try:
x = int(input("Enter a number: "))
result = 10 / x
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Please enter a valid number.")
else:
print("The result is:", result)
finally:
print("Execution completed.")
- In this example, the
tryblock contains code that might raise aValueErrororZeroDivisionError. - The
exceptblocks handle those exceptions accordingly. - The
elseblock executes if no exceptions were raised. - The
finallyblock runs whether an exception occurred or not, ensuring cleanup or logging.
Subtopic 3: Raising Exceptions
In some cases, you might want to manually raise exceptions in your program. You can do this using the raise statement. This can be useful when you want to signal that something went wrong or if you want to enforce certain conditions in your code.
Syntax:
raise ExceptionType("Error message")
Example of Raising an Exception:
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18")
else:
print("Access granted")
try:
check_age(15)
except ValueError as e:
print("Error:", e)
In this example, the check_age function raises a ValueError if the provided age is less than 18.
Subtopic 4: Creating Custom Exceptions
You can create your own exceptions by subclassing the built-in Exception class. Custom exceptions are helpful for defining more specific error conditions in your code.
Syntax:
class CustomError(Exception):
pass
Example of a Custom Exception:
class InvalidAgeError(Exception):
def __init__(self, message="Age is not valid"):
self.message = message
super().__init__(self.message)
def check_age(age):
if age < 18:
raise InvalidAgeError("Age must be at least 18")
print("Access granted")
try:
check_age(16)
except InvalidAgeError as e:
print("Error:", e)
In this example, the InvalidAgeError class inherits from Exception and is raised when the age is invalid. The exception is caught and handled in the except block.
Tasks
-
Task 1: Handling File Not Found Error
- Write a program that asks the user for a filename and attempts to open the file. Use exception handling to catch and handle the case where the file does not exist.
-
Task 2: Custom Exception for Invalid Input
- Create a function that accepts a numeric input from the user. If the input is not a number, raise a custom exception with an appropriate error message.
-
Task 3: Using
finallyBlock- Create a program that connects to a database. Ensure that the connection is closed properly in the
finallyblock, whether or not the connection was successful.
- Create a program that connects to a database. Ensure that the connection is closed properly in the
-
Task 4: Multiple
exceptBlocks- Write a program that asks the user to input two numbers and divides the first by the second. Handle both
ZeroDivisionErrorandValueErrorusing separateexceptblocks.
- Write a program that asks the user to input two numbers and divides the first by the second. Handle both
-
Task 5: Raising Custom Exception
- Create a custom exception class called
InsufficientFundsError. Use it to raise an exception in awithdrawmethod if the account balance is insufficient.
- Create a custom exception class called
-
Task 6: Catching Multiple Exceptions
- Write a program that attempts to divide two numbers and catches multiple exceptions such as
ZeroDivisionError,ValueError, andTypeError.
- Write a program that attempts to divide two numbers and catches multiple exceptions such as