Exception Handling
What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions.
Whenever an exception occurs, the program
stops the execution, and thus the further code
is not executed. Therefore, an exception is a Python object that represents an error.
Exception Handling
Exception Handling is the process of responding to and managing exceptions in a controlled
manner to prevent the program from crashing.
Python uses try and except blocks to handle exceptions.
Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Code that handles the exception
Examples
except Statement with No Exception Type
In Python, the except statement can be used without specifying any exception type. This
allows it to catch all exceptions, regardless of their type.
Example
try:
num = int(input("Enter a number: ")) # Code that may cause an exception
result = 10 / num
except:
print("An error occurred. Something went wrong.")
Common Exceptions
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. ValueError : Raised when a function receives an argument of the correct type but
with an invalid value.
3. TypeError : Raised when an operation or function is applied to an object of an
inappropriate type.
4. NameError: It occurs when a name is not found. It may be local or global.
5. IOError: It occurs when Input Output operation fails.
6. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
7. FileNotFoundError: Raised when trying to open a file that does not exist.
8. IndentationError : Raised when the indentation of the code is incorrect.
try...finally Block
In Python, the try...finally block provides a structured way to handle errors (exceptions) and
ensure some code always runs.
Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code to run if there is no exception
finally:
# Code that runs no matter what
Explanation of Each Block
1. try:
This block contains code that might raise an exception (error).
2. except:
This block runs only if an exception occurs in the try block.
3. else:
This block runs only if no exception occurs in the try block.
4. finally:
This block runs no matter what happens, whether an exception occurs or not.
Example
try:
num = int(input("Enter a number: ")) # Code that may cause an exception
result = 10 / num
except ZeroDivisionError: # Handles division by zero
print("Error: Cannot divide by zero.")
except ValueError: # Handles invalid input
print("Error: Invalid input. Please enter a number.")
else:
# Runs only if no exception occurs
print("Success! Result =”, result)
finally:
# Always runs
print("Execution completed.")
Raise
The raise keyword is used to manually raise an exception in Python.
You want to stop a function or program if a specific condition is met. You can raise an
exception to inform the user or stop execution.
Example
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
print("Your age is:", age)
Output:
1. When input is valid like 25:
Your age is: 25
2. When input is Negative like -5:
ValueError: Age cannot be negative!
Here, the raise statement directly triggers the exception without handling it.