Exception Handling
What is Exception Handling?
Exception handling helps a program respond safely when something unexpected happens, instead of suddenly stopping.
Layman Example
You are withdrawing money from an ATM. Possible problems:
- You enter the wrong PIN
- Your account has insufficient balance
- The ATM has no cash
- The banking server is unavailable
The ATM should not switch off because of these problems. It should display a helpful message.
Try the operation → If a problem occurs, handle it → Continue or close the program safely
What is an Exception?
An exception is an error that occurs while the program is running.
number = 10 / 0
ZeroDivisionError: division by zero
age = int("twenty")
ValueError: invalid literal for int() with base 10: 'twenty'
Types of Errors
1. Syntax Error
The program does not follow Python grammar.
if age > 18
print("Eligible")
SyntaxError: expected ':'
2. Runtime Error (Exception)
The syntax is correct, but an error occurs during execution.
print(10 / 0)
ZeroDivisionError: division by zero
3. Logical Error
The program runs, but the answer is wrong.
price = 1000
discount = 10
final_price = price - discount
print(final_price)
990
Exception handling mainly handles runtime errors.
Basic try and except
try:
# risky code
except:
# code to handle the problem
try:
number = int(input("Enter a number: "))
result = 100 / number
print(result)
except:
print("Something went wrong")
Enter a number: 0 Something went wrong
However, using only
except: is usually not recommended because it hides the actual reason.
Handling Specific Exceptions
try:
number = int(input("Enter a number: "))
result = 100 / number
print("Result:", result)
except ValueError:
print("Please enter numbers only")
except ZeroDivisionError:
print("Zero is not allowed")
Enter a number: 6 Result: 16.666666666666668
1. Users receive meaningful messages
2. Developers can understand the exact problem
3. Unrelated errors are not silently hidden
Complete Structure: try / except / else / finally
- try → contains code that might fail
- except → runs when an exception occurs
- else → runs only when no exception occurs
- finally → runs whether an exception occurs or not
try:
amount = float(input("Enter the withdrawal amount: "))
balance = 10000
remaining_balance = balance - amount
except ValueError:
print("Please enter a valid amount")
else:
print("Withdraw successfully.")
print("Remaining balance:", remaining_balance)
finally:
print("Thank you for using our ATM")
Enter the withdrawal amount: 12000 Withdraw successfully. Remaining balance: -2000.0 Thank you for using our ATM
finally is mainly used for cleanup activities:closing a file, closing a database connection, releasing a network connection, etc.
The raise Statement
raise is used to manually generate an exception when a business rule is violated.
def withdraw(balance, amount):
if amount > balance:
raise ValueError("Insufficient balance")
return balance - amount
raise allows you to report a problem in a controlled way.
Custom Exceptions
We create our own exception classes to give meaningful names to application-specific problems.
class BankCampaignError(Exception):
pass
class DatasetFileError(BankCampaignError):
pass
class EmptyDatasetError(BankCampaignError):
pass
class SchemaValidationError(BankCampaignError):
pass
class DataQualityError(BankCampaignError):
pass
class PipelineExecutionError(BankCampaignError):
pass
Real World Pandas Example
Suppose we need to read a customer CSV file and handle multiple possible problems.
import pandas as pd
try:
bank = pd.read_csv("/content/bank_market.csv")
required_columns = ["age", "job", "default"]
missing_columns = [
column for column in required_columns
if column not in bank.columns
]
if missing_columns:
raise ValueError(f"Missing required columns: {missing_columns}")
except FileNotFoundError:
print("Bank market file was not found")
except pd.errors.EmptyDataError:
print("The CSV file is empty")
except pd.errors.ParserError:
print("The CSV file format is incorrect")
except ValueError as error:
print("Data validation failed:", error)
else:
print("Customer data loaded successfully.")
print(bank.head())
finally:
print("CSV processing completed")
Customer data loaded successfully. Cust_num age job marital education default balance housing \ 0 1 58 management married tertiary no 2143 yes 1 2 44 technician single secondary no 29 yes 2 3 33 entrepreneur married secondary no 2 yes 3 4 47 blue-collar married unknown no 1506 yes 4 5 33 unknown single unknown no 1 no loan contact day month duration campaign pdays previous poutcome y 0 no unknown 5 may 261 1 -1 0 unknown no 1 no unknown 5 may 151 1 -1 0 unknown no 2 yes unknown 5 may 76 1 -1 0 unknown no 3 no unknown 5 may 92 1 -1 0 unknown no 4 no unknown 5 may 198 1 -1 0 unknown no CSV processing completed
Logging Exceptions
In production applications, errors should be recorded instead of only printed.
import logging
logging.basicConfig(
filename="Application.log",
level=logging.ERROR,
format="%(asctime)s - %(levelname)s - %(message)s"
)
try:
result = 100 / 0
except ZeroDivisionError:
logging.exception("Division operation failed")
print("Unable to complete the calculation")
Unable to complete the calculation
logging.exception() records: date & time, error message, exception type, and complete traceback.
Retry Mechanism
Some operations can temporarily fail (for example API or database connections).
import time
def connect_to_server():
raise ConnectionError("Server is unavailable.")
maximum_attempts = 3
for attempt in range(1, maximum_attempts + 1):
try:
connect_to_server()
print("Connected successfully")
break
except ConnectionError as error:
print(f"Attempt {attempt} failed:", error)
if attempt == maximum_attempts:
print("All connection attempts failed")
else:
time.sleep(2)
Attempt 1 failed: Server is unavailable. Attempt 2 failed: Server is unavailable. Attempt 3 failed: Server is unavailable. All connection attempts failed
Summary
try→ attempt the workexcept→ manage the problemelse→ confirms successfinally→ complete the cleanupraise→ report a business rule violation- Custom exception → give the problem a meaningful name
Interview Questions
- What is the difference between an error and an exception?
An error is a general problem. An exception is a runtime problem that can usually be detected and handled. - What is the difference between else and finally?
elseruns only when no exception occurs.finallyruns whether an exception occurs or not. - Can one try have multiple except blocks?
Yes. This allows different exception types to be handled safely. - What does raise do?
It manually generates an exception. - Why create custom exceptions?
They provide meaningful names for application-specific problems (e.g. InsufficientBalanceError).
Exception Handling in Python
Learn how to handle runtime errors safely using try, except, else, finally, raise and custom exceptions.
Select any topic from the left sidebar to begin.
Start Learning →
