- 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)
Add to Bookmark1. 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
- SQL Interview Questions for 5+ Years Experience
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
Random Blogs
- Datasets for Exploratory Data Analysis for Beginners
- Understanding HTAP Databases: Bridging Transactions and Analytics
- The Beginner’s Guide to Normalization and Denormalization in Databases
- Create Virtual Host for Nginx on Ubuntu (For Yii2 Basic & Advanced Templates)
- Datasets for analyze in Tableau
- AI in Cybersecurity: The Future of Digital Protection
- Loan Default Prediction Project Using Machine Learning
- Data Analytics: The Power of Data-Driven Decision Making
- The Ultimate Guide to Starting a Career in Computer Vision
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Grow your business with Facebook Marketing
- Career Guide: Natural Language Processing (NLP)
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- 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