An exception is an error that occurs while a Python program is running. Exception handling allows us to detect and handle these errors so that the program can respond properly instead of stopping unexpectedly.
try, except, else,
and finally blocks to handle exceptions.
An exception is an event that interrupts the normal flow of a program because something unexpected happened during execution.
For example:
number = 10
result = number / 0
print(result)
The program cannot divide a number by zero, so Python raises an exception.
The try block contains code that may raise an exception.
The except block handles the exception.
try:
number = 10 / 0
except:
print("An error occurred")
It is generally better to catch a specific exception when you know what kind of error may occur.
try:
number = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
ZeroDivisionError occurs when a number is divided by zero.
try:
result = 20 / 0
except ZeroDivisionError:
print("Division by zero is not allowed")
ValueError occurs when a function receives a value of the
correct general type but an inappropriate value.
try:
age = int("abc")
except ValueError:
print("Please enter a valid number")
TypeError occurs when an operation is applied to an
inappropriate type.
try:
result = "10" + 5
except TypeError:
print("Incompatible data types")
NameError occurs when Python cannot find a name that has
not been defined.
try:
print(username)
except NameError:
print("Variable is not defined")
IndexError occurs when you try to access a list or sequence
using an index that does not exist.
numbers = [10, 20, 30]
try:
print(numbers[5])
except IndexError:
print("Index does not exist")
KeyError occurs when you try to access a dictionary using
a key that does not exist.
student = {
"name": "Amit",
"age": 20
}
try:
print(student["mobile"])
except KeyError:
print("Key does not exist")
FileNotFoundError occurs when Python tries to open a file
that does not exist at the specified location.
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found")
A program can have multiple except blocks to handle
different types of exceptions.
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Please enter a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
Each exception type can have its own handling logic.
Multiple exception types can be handled by one except block
using a tuple.
try:
number = int("abc")
except (ValueError, TypeError):
print("Invalid value")
You can store the exception object using as and display
its message.
try:
result = 10 / 0
except ZeroDivisionError as error:
print(error)
The else block runs when no exception occurs in the
try block.
try:
number = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Calculation successful")
The finally block executes whether an exception occurs or not.
It is commonly used for cleanup operations.
try:
number = 10 / 2
except ZeroDivisionError:
print("Error")
finally:
print("Program finished")
Python allows all four blocks to be used together.
try:
number = 10 / 2
except ZeroDivisionError:
print("Error occurred")
else:
print("No error occurred")
finally:
print("Execution completed")
The raise statement is used when you want to explicitly
raise an exception.
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
marks = 120
if marks > 100:
raise ValueError("Marks cannot be greater than 100")
Custom messages make errors easier to understand.
Exception handling is especially useful when working with user input.
try:
age = int(input("Enter your age: "))
print("Your age is:", age)
except ValueError:
print("Please enter a valid number")
If the user enters text instead of a valid integer, the program handles the error without terminating at that point.
try:
file = open("data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("The file does not exist")
finally:
print("File operation completed")
The finally block can be used for cleanup logic. For file
handling, the with open(...) pattern is usually preferred
because it handles closing the file automatically.
| Exception | Meaning |
|---|---|
| ValueError | Invalid value for an operation. |
| TypeError | Invalid operation for the given data type. |
| ZeroDivisionError | Division or modulo operation by zero. |
| NameError | A name is not defined. |
| IndexError | Sequence index is out of range. |
| KeyError | Dictionary key does not exist. |
| FileNotFoundError | Requested file does not exist. |
| ImportError | An import cannot be completed. |
try block focused on code that may fail.finally for cleanup operations when appropriate.raise when invalid application state should be reported explicitly.A SyntaxError occurs when Python cannot understand the program's syntax before the affected code can execute normally.
if True
print("Hello")
An exception usually occurs while executing valid Python code because an unexpected condition occurs.
number = 10
result = number / 0
Understanding this difference helps when debugging Python programs.
try contains code that may raise an exception.except handles an exception.else runs when the try block completes without an exception.finally runs whether an exception occurs or not.raise can explicitly raise an exception.Question: Which block is used to handle an exception in Python?