Loading notes...
Loading notes...
BCA • Chapter 8
Chapter 8 teaches how to make software robust by intercepting and handling runtime errors using try, except, else, and finally blocks, as well as raising custom exceptions.
No matter how well you write your code, external factors will inevitably cause it to fail. A user might enter a letter when you expected a number, a network connection might drop, or a file might go missing. When Python encounters an error during execution, it raises an Exception. If this exception is not handled, the program crashes instantly. Exception handling allows you to intercept these errors, execute fallback code, and keep your program running smoothly.
8.1 Syntax Errors vs. Exceptions
It is important to distinguish between Syntax Errors and Exceptions (Runtime Errors). Syntax Errors occur before the code even runs because the grammar of the Python language was violated (e.g., missing a colon). Exceptions occur while the code is running, when a syntactically correct statement fails (e.g., dividing by zero).
8.2 The try and except Blocks
The core of exception handling involves wrapping risky code inside a `try` block. If the code inside the `try` block executes successfully, the `except` block is skipped. If an error occurs, the rest of the `try` block is aborted, and Python jumps immediately to the `except` block.
try:
# Risky code
num = int(input("Enter a number: "))
result = 100 / num
print(f"Result is {result}")
except ZeroDivisionError:
# Handles division by zero
print("Error: You cannot divide by zero!")
except ValueError:
# Handles invalid input (like typing 'abc' instead of a number)
print("Error: Please enter a valid integer.")
except Exception as e:
# Catch-all for any other unexpected errors
# 'as e' captures the error object so we can print the exact reason
print(f"An unexpected error occurred: {e}")8.3 The else and finally Blocks
Python's exception handling provides two additional, optional blocks: `else` and `finally`.
try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("The file is missing.")
else:
print("File read successfully! Length:", len(data))
finally:
# This will run whether the file was found or not
print("Execution of try-except block finished.")
# Note: Checking if 'file' exists before closing is best practice here8.4 Raising Exceptions Manually
As a developer, you might write a function that requires specific input to work properly. If the user provides bad data, you can actively trigger an error using the `raise` keyword. This forces the calling code to handle the problem.
def set_age(age):
if age < 0:
# Manually triggering a ValueError with a custom message
raise ValueError("Age cannot be negative.")
print(f"Age set to {age}")
try:
set_age(-5)
except ValueError as e:
print(f"Caught an error: {e}")8.5 Custom User-Defined Exceptions
For large applications, the built-in exceptions (ValueError, TypeError) might not be descriptive enough for your specific business logic. You can create your own custom exception classes by inheriting from Python's base `Exception` class.
# Defining a custom exception
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(f"Cannot withdraw {amount}. Balance is {balance}.")
return balance - amount
try:
new_balance = withdraw(100, 500)
except InsufficientFundsError as e:
print(f"Transaction Denied: {e}")