Friday, 24 April 2026

April Python Bootcamp Day 15

 




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

  1. Write a program that takes a number as input and handles invalid input using try-except.
  2. Create a program that divides two numbers and handles division by zero.
  3. Demonstrate the use of else in exception handling.

Intermediate Level

  1. Write a program to open a file and handle the case when the file does not exist.
  2. Handle multiple exceptions (ValueError, ZeroDivisionError) in a single block.
  3. Capture and print exception details using as.

Advanced Level

  1. Create a custom exception called NegativeNumberError and raise it when a negative number is entered.
  2. Build a login system that raises an exception if the password is incorrect.
  3. Modify the bank withdrawal system to:
    • Allow multiple transactions
    • Update balance after withdrawal
    • Handle invalid inputs

Challenge Question

  1. Create a menu-driven program that:
  • Takes user input
  • Performs operations (division, file reading, etc.)
  • Uses proper exception handling for all cases

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (249) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (29) Azure (10) BI (10) Books (262) Bootcamp (10) C (78) C# (12) C++ (83) Course (87) Coursera (300) Cybersecurity (30) data (5) Data Analysis (32) Data Analytics (22) data management (15) Data Science (349) Data Strucures (17) Deep Learning (154) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (71) Git (10) Google (51) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (42) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (287) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (14) PHP (20) Projects (32) pytho (1) Python (1319) Python Coding Challenge (1130) Python Mistakes (51) Python Quiz (485) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (49) Udemy (18) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)