- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Exception Handling
Exception Handling is used to manage runtime errors and prevent programs from crashing.
Exceptions occur when:
- User enters invalid input
- File not found
- Network connection fails
- Wrong operations (divide by zero)
Basic Structure
try:
# Code that may throw error
except:
# Code to run if error occurs
Basic Example
try:
a = 10 / 0
except:
print("Cannot divide by zero!")
Catching Specific Exceptions
try:
a = int("abc")
except ValueError:
print("Value Error occurred: Invalid conversion to integer")
Multiple Except Blocks
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Only numbers are allowed.")
Using else Block
Runs only when no exception occurs.
try:
x = int(input("Enter age: "))
except ValueError:
print("Invalid input.")
else:
print("Valid age:", x)
Using finally Block
Always runs — even if an error occurs.
try:
f = open("data.txt")
except FileNotFoundError:
print("File not found!")
finally:
print("Program finished.")
Raise an Exception Yourself
Use raise for rules/validation.
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Custom Exception
class InvalidAgeError(Exception):
pass
age = 15
if age < 18:
raise InvalidAgeError("You must be 18+ to sign up")
File Handling with Exception
try:
f = open("notes.txt", "r")
print(f.read())
except FileNotFoundError:
print("File does not exist.")
finally:
print("Closing file if opened.")
Multiple Exceptions in One Line
try:
x = 10 / int("a")
except (ZeroDivisionError, ValueError):
print("Error: Invalid operation")
Catch All Exceptions
try:
a = 10 / 0
except Exception as e:
print("Error occurred:", e)
Common Built-in Exceptions
| Exception | When it Occurs |
|---|---|
| ZeroDivisionError | Divide by zero |
| ValueError | Wrong data type in conversion |
| TypeError | Unsupported operations between types |
| FileNotFoundError | File does not exist |
| KeyError | Key not found in dictionary |
| IndexError | Index out of range |
| NameError | Variable not defined |
| ImportError | Module not found |
Real-Time Examples
User Input Validation
while True:
try:
amount = float(input("Enter amount: "))
break
except ValueError:
print("Enter a valid number!")
Retry File Opening Automatically
for _ in range(3):
try:
f = open("config.json")
print("File opened!")
break
except FileNotFoundError:
print("File missing, retrying...")
API Request Error Handling (Concept)
try:
data = fetch_api_data()
except ConnectionError:
print("Network issue!")