What is Exception Handling?
Exception handling is the process of responding to runtime errors so that the normal flow of the program is not interrupted.
Example without Exception Handling
num = int(input("Enter a num: "))
print(10 / num)
print("Hello World")
If the user enters 0 or invalid input, the program crashes and "Hello World" will not execute.
try - except Block
To prevent crashes, Python provides the try-except mechanism.
- try → Code that may cause an error
- except → Code that handles the error
Basic Example
try:
num = int(input("Enter a num: "))
print(10 / num)
except:
print("Something went wrong!")
print("Hello World")
Now, even if an error occurs, the program continues execution.
Handling Specific Exceptions
Handling specific exceptions is always better than using a general except.
Example
try:
num = int(input("Enter a num: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input! Please enter a number")
except:
print("Unaware of the error")
print("Hello World")
This improves debugging and makes your code more precise.
else and finally
Python provides two additional blocks:
- else → Runs when no exception occurs
- finally → Always runs
Example
try:
file = open("data.txt", "r")
print(file.read())
except FileNotFoundError as e:
print("File Not Found", e)
else:
print("Found the file")
finally:
print("Execution completed")
Multiple Exceptions in One Block
You can handle multiple exceptions together:
try:
num = int(input("Enter a num: "))
print(10 / num)
except (ValueError, ZeroDivisionError):
print("Something went wrong!")
Using Exception Objects
You can capture the exception details using as.
try:
x = int("abc")
except ValueError as e:
print("Error:", e)
Raising Exceptions Manually
You can trigger exceptions using the raise keyword.
age = int(input("Enter age: "))
if age < 18:
raise ValueError("You must be 18 or older")
print("Access Granted")
Custom Exceptions
You can define your own exception classes by inheriting from Exception.
Example
class MyError(Exception):
pass
raise MyError("This is a custom error")
Real-World Example: Bank Withdrawal System
class InsufficientBalanceError(Exception):
pass
balance = 5000
withdraw = int(input("Enter amount to withdraw"))
try:
if withdraw > balance:
raise InsufficientBalanceError("Not enough balance")
else:
print("Withdrawal successful")
except InsufficientBalanceError as e:
print(e)
This demonstrates how custom exceptions can model real-world scenarios.
Best Practices
- Always handle specific exceptions instead of generic ones
- Use finally for cleanup tasks (closing files, releasing resources)
- Avoid silent failures (empty except)
- Use custom exceptions for domain-specific logic
Assignment Questions
Basic Level
- Write a program that takes a number as input and handles invalid input using try-except.
- Create a program that divides two numbers and handles division by zero.
- Demonstrate the use of else in exception handling.
Intermediate Level
- Write a program to open a file and handle the case when the file does not exist.
- Handle multiple exceptions (ValueError, ZeroDivisionError) in a single block.
- Capture and print exception details using as.
Advanced Level
- Create a custom exception called NegativeNumberError and raise it when a negative number is entered.
- Build a login system that raises an exception if the password is incorrect.
-
Modify the bank withdrawal system to:
- Allow multiple transactions
- Update balance after withdrawal
- Handle invalid inputs
Challenge Question
- Create a menu-driven program that:
- Takes user input
- Performs operations (division, file reading, etc.)
- Uses proper exception handling for all cases
.png)

0 Comments:
Post a Comment