- 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 5+ Years Experience
- JavaScript Interview Questions for 2–5 Years Experience
- JavaScript Interview Questions for 1–2 Years Experience
- 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
Random Blogs
- Top 10 Blogs of Digital Marketing you Must Follow
- Store Data Into CSV File Using Python Tkinter GUI Library
- How Multimodal Generative AI Will Change Content Creation Forever
- 15 Amazing Keyword Research Tools You Should Explore
- How to Start Your Career as a DevOps Engineer
- Understanding HTAP Databases: Bridging Transactions and Analytics
- Time Series Analysis on Air Passenger Data
- Mastering Python in 2025: A Complete Roadmap for Beginners
- Understanding LLMs (Large Language Models): The Ultimate Guide for 2025
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Why to learn Digital Marketing?
- Career Guide: Natural Language Processing (NLP)
- 10 Awesome Data Science Blogs To Check Out
- Loan Default Prediction Project Using Machine Learning
- Government Datasets from 50 Countries for Machine Learning Training
Datasets for Machine Learning
- Awesome-ChatGPT-Prompts
- 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


