- 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
- JavaScript Interview Questions for 0–1 Year Experience
- JavaScript Interview Questions For Fresher
- 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
Random Blogs
- SQL Joins Explained: A Complete Guide with Examples
- What is YII? and How to Install it?
- Ideas for Content of Every niche on Reader’s Demand during COVID-19
- Loan Default Prediction Project Using Machine Learning
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- Understanding HTAP Databases: Bridging Transactions and Analytics
- Understanding OLTP vs OLAP Databases: How SQL Handles Query Optimization
- Datasets for Exploratory Data Analysis for Beginners
- Internet of Things (IoT) & AI – Smart Devices and AI Working Together
- What Is SEO and Why Is It Important?
- How to Start Your Career as a DevOps Engineer
- The Beginner’s Guide to Normalization and Denormalization in Databases
- Time Series Analysis on Air Passenger Data
- Avoiding the Beginner’s Trap: Key Python Fundamentals You Shouldn't Skip
- Transforming Logistics: The Power of AI in Supply Chain Management
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