Exception Handling in Python
What is an Exception?
An exception is an error that occurs during the execution of a program and stops the normal flow of the program.
Example of an Exception
print(10 / 0)
This causes a ZeroDivisionError because a number cannot be divided by zero.
What is Exception Handling?
Exception handling in Python is a way to handle runtime errors so that the program does not crash and can continue running smoothly.
Python handles exceptions using:
- try
- except
- else
- finally
1. try and except
The try block contains code that may cause an error.
The except block handles the error if it occurs.
Example
try:
x = 10 / 0
print(x)
except:
print("Error: Cannot divide by zero")
Explanation
- Python tries to execute the code inside
try. 10 / 0causes an error.- Instead of crashing, control goes to the
exceptblock. - The error message is printed safely.
2. Handling Specific Exceptions
We can handle specific types of errors.
Example
try:
num = int("abc")
except ValueError:
print("ValueError: Invalid number")
Explanation
"abc"cannot be converted to an integer.- Python raises a
ValueError. - The matching
except ValueErrorblock handles it. - This makes error handling more accurate.
3. try with else
The else block runs only if no exception occurs.
Example
try:
a = 10
b = 2
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful")
Explanation
- No error occurs in the
tryblock. - The
exceptblock is skipped. - The
elseblock executes successfully.
4. finally Block
The finally block always executes, whether an exception
occurs or not.
Example
try:
file = open("data.txt", "r")
print(file.read())
except:
print("File not found")
finally:
print("Program finished")
Explanation
- Python tries to open the file.
- If the file exists, it reads it.
- If not, an error message is printed.
- The
finallyblock runs in all cases.
5. Raising an Exception
We can manually raise an exception using the raise keyword.
Example
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Explanation
- The condition checks if age is negative.
raiseforces aValueError.- This is useful for validating input.
Common Built-in Exceptions
- ZeroDivisionError → Division by zero
- ValueError → Invalid value
- TypeError → Wrong data type
- IndexError → Index out of range
- KeyError → Missing dictionary key