Exception Handling is the process of handling runtime errors in a program. It prevents the program from crashing and allows it to continue running smoothly.
An exception is an error that occurs during program execution.
Common Exceptions
| Exception | Description |
|---|---|
ZeroDivisionError | Division by zero |
ValueError | Invalid value |
TypeError | Invalid operation between data types |
NameError | Variable not defined |
IndexError | Invalid list index |
KeyError | Dictionary key not found |
FileNotFoundError | File does not exist |
Handling ZeroDivisionError
Example
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
Handling ValueError
Example
try:
age = int("abc")
except ValueError:
print("Invalid value")
Output:
Invalid value
Handling TypeError
Example
try:
result = "10" + 10
except TypeError:
print("Type mismatch")
Output:
Type mismatch
Handling NameError
Example
try:
print(username)
except NameError:
print("Variable not found")
Output:
Variable not found
Handling IndexError
Example
try:
numbers = [10, 20, 30]
print(numbers[5])
except IndexError:
print("Index out of range")
Output:
Index out of range
Handling KeyError
Example
try:
student = {"name": "John"}
print(student["age"])
except KeyError:
print("Key not found")
Output:
Key not found
Handling FileNotFoundError
Example
try:
file = open("data.txt")
except FileNotFoundError:
print("File not found")
Output:
File not found
Handling Multiple Exceptions
Example
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
Using Exception as a Variable
Example
try:
print(10 / 0)
except Exception as error:
print(error)
Output:
division by zero
Raising Exceptions
You can create exceptions manually using the raise keyword.
Example
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Output:
ValueError: Age cannot be negative
Custom Exceptions
Example
class InvalidAgeError(Exception):
pass
age = -1
if age < 0:
raise InvalidAgeError("Invalid Age")
Output:
InvalidAgeError: Invalid Age
Summary
- Exception handling manages runtime errors.
- Exceptions prevent programs from crashing unexpectedly.
- Different exception types handle different errors.
- Multiple exceptions can be handled separately.
- The
raisekeyword creates exceptions manually. - Custom exceptions can be created by inheriting from
Exception. - Proper exception handling improves application reliability.