Exception handling
Exception handling in Python allows you to manage runtime errors—unexpected events like dividing by zero or
missing files—without crashing the program.
1. Core Keywords
Python uses a specific set of keywords to handle exceptions:
Wraps the code that might cause an error.
Contains the code that runs if an exception occurs in the block.
Executes code only if no exceptions were raised in the block.
Executes code regardless of whether an exception occurred, typically for cleanup tasks like closing files.
Manually triggers an exception.
2. Basic Example
3. Key Concepts
Specific Exceptions: It is best practice to catch specific exceptions (e.g., ) rather than using a "bare" clause, which can
hide unrelated bugs.
Multiple Exceptions: You can catch multiple exceptions in a single block using a tuple:
Custom Exceptions: You can define your own errors by creating a new class that inherits from the built-in class.
Exception Chaining: Python 3 allows you to raise a new exception while preserving the original traceback using the
syntax.
4. Common Built-in Exceptions
Exception Triggered When...
SyntaxError It is raised when there is an error in the syntax of the Python code.
while True print('Hello world')
SyntaxError: invalid syntax
IOError It is raised when the file specified in a program statement cannot be opened.
Eg: with open("[Link]", "r") as f:
IOError: [Errno 2] No such file or directory: '[Link]'
KeyboardInterrupt It is raised when the user accidentally hits the Delete or Esc key while executing a
Error program due to which the normal flow of the program is interrupted.
ImportError
It is raised when the requested module definition is not found.
Eg: from module_a import function_a
def function_b():
print("Function B")
ZeroDivisionError Dividing a number by zero. Eg: 10 * (1/0)
EOFError It is raised when the end of file condition is reached without reading any data by
input().
NameError It is raised when a local or global variable name is not defined. Eg: 4+spam*3
TypeError An operation is performed on an inappropriate data type (e.g., 1 + "1")
Eg: len(100), range(‘10’), “hello”+5, int(5,2), [1,2,3]+5, “abc”[1.2], max(10),
sorted(100).
ValueError A function receives an argument of the correct type but invalid value].
Eg: int(‘a’), float(“abc”), [Link](-4), “hello”.index(“k”), [11,12,16].remove(13),
int(“12.5”), range(1,10,0)
IndexError Attempting to access a list index that is out of range.
Eg: x = ["apple", "banana"]
# print(x[2]) # Raises IndexError: list index out of range
print(x[1]) # Correct: accesses "banana"
KeyError Accessing a dictionary with a key that does not exist.
FileNotFoundError Trying to open a file that does not exist.
OverFlowError It is raised when the result of a calculation exceeds the maximum limit for numeric
data type.
Eg: import math
try:
print([Link](999))
except OverflowError:
print("Calculation resulted in a number too large.")