- Python Basics
-
Overview
- Introduction to Python and Installation
- Variables and Data Types
- Conditional Statements (if-else)
- Loops (for, while)
- Functions and Lambda Expressions
- Lists, Tuples, and Dictionaries
- File Handling (Reading/Writing Files)
- Exception Handling (Try, Except)
- Modules and Packages
- List Comprehensions and Generators
Exception Handling (Try, Except)
1. Introduction
Exception handling in Python helps manage errors gracefully without crashing the program. It uses the try
, except
, else
, and finally
blocks to catch and handle exceptions.
2. Understanding Exceptions
An exception is an error that occurs during execution, stopping the program.
Common Exceptions in Python
Exception | Cause |
---|---|
ZeroDivisionError | Division by zero (5 / 0 ) |
TypeError | Invalid type operation ("5" + 5 ) |
ValueError | Incorrect value format (int("abc") ) |
FileNotFoundError | Trying to open a non-existent file |
IndexError | Accessing an invalid index in a list |
KeyError | Accessing a non-existent key in a dictionary |
3. Using Try and Except
The try
block runs the code, and if an error occurs, the except
block executes.
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a number.")
If the user enters 0
, ZeroDivisionError
is handled.
If the user enters "abc"
, ValueError
is handled.
4. Catching Multiple Exceptions
You can handle multiple exceptions in a single except
block.
try:
num = int(input("Enter a number: "))
result = 10 / num
except (ZeroDivisionError, ValueError) as e:
print("An error occurred:", e)
as e
stores the actual error message.
5. Using Else with Try-Except
The else
block runs if no exception occurs.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
else:
print("Successful! The result is:", result)
If no exception occurs, the else
block runs.
If an error occurs, the else
block is skipped.
6. Finally Block
The finally
block always executes, whether an exception occurs or not.
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing file (if opened).")
if 'file' in locals():
file.close()
The finally
block is useful for cleanup operations like closing files or releasing resources.
7. Raising Exceptions Manually
You can raise exceptions using raise
.
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("You must be at least 18 years old.")
This manually triggers a ValueError
if the user enters an age below 18.
8. Summary
Use try
to test code that might cause an error.
Use except
to handle specific errors.
Use else
to execute code when no exception occurs.
Use finally
to execute cleanup operations.
Use raise
to manually trigger exceptions.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- 15 Amazing Keyword Research Tools You Should Explore
- Top 15 Recommended SEO Tools
- Understanding HTAP Databases: Bridging Transactions and Analytics
- Generative AI - The Future of Artificial Intelligence
- The Ultimate Guide to Machine Learning (ML) for Beginners
- How to Start Your Career as a DevOps Engineer
- Types of Numbers in Python
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Big Data: The Future of Data-Driven Decision Making
- Datasets for Speech Recognition Analysis
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Google’s Core Update in May 2020: What You Need to Know
- Variable Assignment in Python
- Why to learn Digital Marketing?
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset