Introduction
Errors are common in programming. When a program encounters an unexpected problem, it may stop executing and display an error message.
In Python, such runtime errors are called Exceptions.
If exceptions are not handled properly, programs may crash unexpectedly. Python provides a powerful mechanism called Exception Handling to manage errors gracefully.
Exception handling allows developers to detect, control, and respond to errors without terminating the program.
This concept is widely used in Artificial Intelligence, Data Science, Web Development, Automation, and Software Engineering.
Learning Objectives
- Understand exceptions in Python.
- Learn the difference between errors and exceptions.
- Use try and except blocks.
- Understand else and finally blocks.
- Use raise statements.
- Create custom exceptions.
- Apply exception handling in real-world applications.
What is an Exception in Python?
An exception is an event that interrupts the normal execution flow of a program.
Exceptions occur during runtime when Python encounters invalid operations.
Example:
print(10/0)
Output:
ZeroDivisionError:
division by zero
Here, Python generates an exception because division by zero is mathematically invalid.
Why Exception Handling is Important
Exception handling is important because it prevents programs from crashing unexpectedly.
Without exception handling:
- Programs terminate immediately.
- User experience becomes poor.
- Data processing may fail.
- Applications become unstable.
Exception handling allows developers to:
- Catch errors.
- Display meaningful messages.
- Continue program execution.
- Improve software reliability.
Common Types of Exceptions
Python provides many built-in exceptions.
| Exception | Description |
|---|---|
| ZeroDivisionError | Division by zero |
| NameError | Undefined variable |
| TypeError | Invalid data type operation |
| ValueError | Invalid value supplied |
| IndexError | Invalid index access |
| FileNotFoundError | Missing file |
The try and except Block
Python uses try and except blocks to handle exceptions.
Syntax
try:
risky code
except:
error handling code
Example
try:
print(10/0)
except:
print("Cannot divide by zero")
Output:
Cannot divide by zero
Instead of crashing, the program handles the error safely.
Handling Specific Exceptions
It is considered a good practice to handle specific exceptions.
Example
try:
value = int("Python")
except ValueError:
print("Invalid Number")
Output:
Invalid Number
Handling Multiple Exceptions
A program can handle multiple exception types.
Example
try:
number = int(input("Enter Number: "))
result = 10/number
except ValueError:
print("Invalid Input")
except ZeroDivisionError:
print("Zero Not Allowed")
The else Block
The else block executes only if no exception occurs.
Example
try:
x = 10/2
except ZeroDivisionError:
print("Error")
else:
print("Success")
Output:
Success
The finally Block
The finally block always executes whether an exception occurs or not.
It is commonly used for cleanup tasks such as closing files or database connections.
Example
try:
print(10/2)
except:
print("Error")
finally:
print("Execution Completed")
Output:
5.0
Execution Completed
The raise Statement
Python allows programmers to manually generate exceptions using the raise keyword.
Example
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Output:
ValueError:
Age cannot be negative
Custom Exceptions
Python allows developers to create their own exception classes.
Example
class InvalidSalary(Exception):
pass
salary = -1000
if salary < 0:
raise InvalidSalary("Salary cannot be negative")
Custom exceptions are useful for large applications and enterprise software.
Exception Handling in Artificial Intelligence
Exception handling is extremely important in Artificial Intelligence and Data Science projects.
Common applications:
- Handling missing datasets.
- Managing invalid model inputs.
- Preventing prediction failures.
- Managing file loading errors.
- Handling API response failures.
AI systems must handle errors carefully because they often work with massive datasets and external resources.
Real-World Examples
Login Validation Example
try:
password = input("Enter Password: ")
if len(password) < 6:
raise ValueError("Password Too Short")
print("Valid Password")
except ValueError as e:
print(e)
ATM Withdrawal Example
balance = 5000
try:
withdraw = 7000
if withdraw > balance:
raise Exception("Insufficient Balance")
except Exception as e:
print(e)
Python Example
try:
number = int(input("Enter Number: "))
print(100/number)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Enter valid integer")
Interview Questions
1. What is an exception in Python?
An exception is a runtime event that interrupts program execution.
2. Which keyword is used to handle exceptions?
The except keyword.
3. What is the purpose of finally?
The finally block executes regardless of whether an exception occurs.
4. What does the raise statement do?
It manually generates exceptions.
Assignment
- Create a division program using try-except.
- Handle ZeroDivisionError.
- Handle ValueError using user input.
- Create a custom exception example.
- Use finally in a file handling example.
Quiz
Q1. Which keyword handles exceptions?
- A. try
- B. except
- C. break
- D. def
Answer: B. except
Q2. Which block always executes?
- A. else
- B. except
- C. finally
- D. try
Answer: C. finally
Q3. Which keyword manually creates exceptions?
- A. import
- B. return
- C. raise
- D. continue
Answer: C. raise
Summary
In this tutorial, you learned Exception Handling in Python. You explored exceptions, try-except blocks, else, finally, raise statements, and custom exceptions.
Exception handling is essential for building reliable applications because it prevents crashes and improves program stability.
Understanding exception handling is important for Artificial Intelligence, Data Science, Automation, and Software Development.
Next Tutorial
Tutorial 19: Modules and Packages
```
