Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
User-defined Exceptions in Python with Examples
Next article icon

Python Exception Handling

Last Updated : 02 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let’s look at an example:

Handling a Simple Exception in Python

Exception handling helps in preventing crashes due to errors. Here’s a basic example demonstrating how to catch an exception and handle it gracefully:

Python
# Simple Exception Handling Example n = 10 try:     res = n / 0  # This will raise a ZeroDivisionError      except ZeroDivisionError:     print("Can't be divided by zero!") 

Output
Can't be divided by zero! 

Explanation: In this example, dividing number by 0 raises a ZeroDivisionError. The try block contains the code that might cause an exception and the except block handles the exception, printing an error message instead of stopping the program.


Difference Between Exception and Error

  • Error: Errors are serious issues that a program should not try to handle. They are usually problems in the code’s logic or configuration and need to be fixed by the programmer. Examples include syntax errors and memory errors.
  • Exception: Exceptions are less severe than errors and can be handled by the program. They occur due to situations like invalid input, missing files or network issues.

Example:

Python
# Syntax Error (Error) print("Hello world"  # Missing closing parenthesis  # ZeroDivisionError (Exception) n = 10 res = n / 0 

Explanation: A syntax error is a coding mistake that prevents the code from running. In contrast, an exception like ZeroDivisionError can be managed during the program’s execution using exception handling.

Syntax and Usage

Exception handling in Python is done using the try, except, else and finally blocks.

try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs

try, except, else and finally Blocks

  • try Block: try block lets us test a block of code for errors. Python will “try” to execute the code in this block. If an exception occurs, execution will immediately jump to the except block.
  • except Block: except block enables us to handle the error or exception. If the code inside the try block throws an error, Python jumps to the except block and executes it. We can handle specific exceptions or use a general except to catch all exceptions.
  • else Block: else block is optional and if included, must follow all except blocks. The else block runs only if no exceptions are raised in the try block. This is useful for code that should execute if the try block succeeds.
  • finally Block: finally block always runs, regardless of whether an exception occurred or not. It is typically used for cleanup operations (closing files, releasing resources).

Example:

Python
try:     n = 0     res = 100 / n      except ZeroDivisionError:     print("You can't divide by zero!")      except ValueError:     print("Enter a valid number!")      else:     print("Result is", res)      finally:     print("Execution complete.") 

Output
You can't divide by zero! Execution complete. 

Explanation:

  • try block asks for user input and tries to divide 100 by the input number.
  • except blocks handle ZeroDivisionError and ValueError.
  • else block runs if no exception occurs, displaying the result.
  • finally block runs regardless of the outcome, indicating the completion of execution.

Common Exceptions in Python

Python has many built-in exceptions, each representing a specific error condition. Some common ones include:

Exception NameDescription
BaseExceptionThe base class for all built-in exceptions.
ExceptionThe base class for all non-exit exceptions.
ArithmeticErrorBase class for all errors related to arithmetic operations.
ZeroDivisionErrorRaised when a division or modulo operation is performed with zero as the divisor.
OverflowErrorRaised when a numerical operation exceeds the maximum limit of a data type.
FloatingPointErrorRaised when a floating-point operation fails.
AssertionErrorRaised when an assert statement fails.
AttributeErrorRaised when an attribute reference or assignment fails.
IndexErrorRaised when a sequence subscript is out of range.
KeyErrorRaised when a dictionary key is not found.
MemoryErrorRaised when an operation runs out of memory.
NameErrorRaised when a local or global name is not found.
OSErrorRaised when a system-related operation (like file I/O) fails.
TypeErrorRaised when an operation or function is applied to an object of inappropriate type.
ValueErrorRaised when a function receives an argument of the right type but inappropriate value.
ImportErrorRaised when an import statement has issues.
ModuleNotFoundErrorRaised when a module cannot be found.

Python Catching Exceptions

When working with exceptions in Python, we can handle errors more efficiently by specifying the types of exceptions we expect. This can make code both safer and easier to debug.

Catching Specific Exceptions

Catching specific exceptions makes code to respond to different exception types differently.

Example:

Python
try:     x = int("str")  # This will cause ValueError          #inverse     inv = 1 / x      except ValueError:     print("Not Valid!")      except ZeroDivisionError:     print("Zero has no inverse!") 

Output
Not Valid! 

Explanation:

  • The ValueError is caught because the string “str” cannot be converted to an integer.
  • If x were 0 and conversion successful, the ZeroDivisionError would be caught when attempting to calculate its inverse.

Catching Multiple Exceptions

We can catch multiple exceptions in a single block if we need to handle them in the same way or we can separate them if different types of exceptions require different handling.

Example:

Python
a = ["10", "twenty", 30]  # Mixed list of integers and strings try:     total = int(a[0]) + int(a[1])  # 'twenty' cannot be converted to int      except (ValueError, TypeError) as e:     print("Error", e)      except IndexError:     print("Index out of range.") 

Output
Error invalid literal for int() with base 10: 'twenty' 

Explanation:

  • The ValueError is caught when trying to convert “twenty” to an integer.
  • TypeError might occur if the operation was incorrectly applied to non-integer types, but it’s not triggered in this specific setup.
  • IndexError would be caught if an index outside the range of the list was accessed, but in this scenario, it’s under control.

Catch-All Handlers and Their Risks

Here’s a simple calculation that may fail due to various reasons.

Example:

Python
try:     # Simulate risky calculation: incorrect type operation     res = "100" / 20      except ArithmeticError:     print("Arithmetic problem.")      except:     print("Something went wrong!") 

Output
Something went wrong! 

Explanation:

  • An ArithmeticError (more specific like ZeroDivisionError) might be caught if this were a number-to-number division error. However, TypeError is actually triggered here due to attempting to divide a string by a number.
  • catch-all except: is used to catch the TypeError, demonstrating the risk that the programmer might not realize the actual cause of the error (type mismatch) without more detailed error logging.

Raise an Exception

We raise an exception in Python using the raise keyword followed by an instance of the exception class that we want to trigger. We can choose from built-in exceptions or define our own custom exceptions by inheriting from Python’s built-in Exception class.

Basic Syntax:

raise ExceptionType(“Error message”)

Example:

Python
def set(age):     if age < 0:         raise ValueError("Age cannot be negative.")     print(f"Age set to {age}")  try:     set(-5) except ValueError as e:     print(e) 

Output
Age cannot be negative. 

Explanation:

  • The function set checks if the age is negative. If so, it raises a ValueError with a message explaining the issue.
  • This ensures that the age attribute cannot be set to an invalid state, thus maintaining the integrity of the data.

Advantages of Exception Handling:

  • Improved program reliability: By handling exceptions properly, you can prevent your program from crashing or producing incorrect results due to unexpected errors or input.
  • Simplified error handling: Exception handling allows you to separate error handling code from the main program logic, making it easier to read and maintain your code.
  • Cleaner code: With exception handling, you can avoid using complex conditional statements to check for errors, leading to cleaner and more readable code.
  • Easier debugging: When an exception is raised, the Python interpreter prints a traceback that shows the exact location where the exception occurred, making it easier to debug your code.

Disadvantages of Exception Handling:

  • Performance overhead: Exception handling can be slower than using conditional statements to check for errors, as the interpreter has to perform additional work to catch and handle the exception.
  • Increased code complexity: Exception handling can make your code more complex, especially if you have to handle multiple types of exceptions or implement complex error handling logic.
  • Possible security risks: Improperly handled exceptions can potentially reveal sensitive information or create security vulnerabilities in your code, so it’s important to handle exceptions carefully and avoid exposing too much information about your program.


Next Article
User-defined Exceptions in Python with Examples

N

Nikhil Kumar Singh
Improve
Article Tags :
  • Python
  • School Programming
Practice Tags :
  • python

Similar Reads

  • Decorators in Python
    In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
    10 min read
  • Help function in Python
    help() function in Python is a built-in function that provides information about modules, classes, functions and modules. It is useful for retrieving information on various Python objects. Example: [GFGTABS] Python help() [/GFGTABS]OutputWelcome to Python 3.13's help utility! If this is your first t
    5 min read
  • __import__() function in Python
    __import__() is a built-in function in Python that is used to dynamically import modules. It allows us to import a module using a string name instead of the regular "import" statement. It's useful in cases where the name of the needed module is know to us in the runtime only, then to import those mo
    2 min read
  • Python Classes and Objects
    A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
    6 min read
  • Constructors in Python
    In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
    3 min read
  • Destructors in Python
    Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
    7 min read
  • Inheritance in Python
    Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
    7 min read
  • Encapsulation in Python
    In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
    6 min read
  • Polymorphism in Python
    Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave differently based on the type of data they are handling. Derived from Greek, the term literally means "many forms". Python's dynamic typing and duck typing make it inherently pol
    7 min read
  • Class method vs Static method in Python
    In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences