Exception Handling
What is an Exception?
An exception is an error that occurs during the execution of a program.
Examples of common exceptions:
ZeroDivisionErrorValueErrorTypeErrorIndexErrorFileNotFoundErrorKeyError
Why Exception Handling?
Without handling → program crashes.
With handling → program continues safely.
try–except Block (Basic Syntax)
try:
# Code that may cause error
except:
# Code to run when error happens
Example
try:
x = 10 / 0
except:
print("Error occurred!")
Handling Specific Exceptions
try:
a = int("hello")
except ValueError:
print("Invalid number")
Multiple except Blocks
try:
num = int(input("Enter number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter digits only")
else Block
Runs only when no exception occurs.
try:
print("No error")
except:
print("Error found")
else:
print("Else block executed")
finally Block
Runs always, even if an error happens.
Useful for:
- Closing files
- Closing database connection
- Releasing resources try: f = open("sample.txt", "r") print(f.read()) except: print("File not found") finally: print("Closing file")
try–except–else–finally (All Together)
python
try:
n = int(input("Enter number: "))
except ValueError:
print("Invalid Input")
else:
print("Square:", n*n)
finally:
print("End of program")
**Raise Your Own Exception**
Use `raise` to throw a custom error.
age = 15
if age < 18:
raise Exception("You must be 18+")
**Custom Exception Class**
class LowBalanceError(Exception):
pass
balance = 300
try:
if balance < 500:
raise LowBalanceError("Balance too low")
except LowBalanceError as e:
print(e)
**Common Python Exceptions Table**
| Exception | Meaning |
| ----------------- | ----------------------- |
| ZeroDivisionError | Division by zero |
| ValueError | Wrong value type |
| TypeError | Wrong data type |
| IndexError | List index out of range |
| KeyError | Dictionary key missing |
| FileNotFoundError | File does not exist |
| ImportError | Module not found |
**Practical Mini Programs (Day 18 Practice)**
**1️⃣ Safe Division Program**
try:
a = int(input("A: "))
b = int(input("B: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Enter numbers only")
**2.File Reader with Exception Handling**
try:
f = open("demo.txt", "r")
print(f.read())
except FileNotFoundError:
print("File doesn't exist")
**3.Convert String to Integer Safely**
def convert(s):
try:
return int(s)
except:
return "Conversion Failed"
print(convert("123"))
print(convert("abc"))
**4.Custom Exception **
**Example**
class InvalidAge(Exception):
pass
try:
age = int(input("Enter age: "))
if age < 18:
raise InvalidAge("Age is below 18")
print("Eligible")
except InvalidAge as e:
print(e)
Top comments (0)