Python Exception Handling
Last Updated :
15 Jan, 2025
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.
Example: Trying to divide a number by zero will cause an exception.
Python
# Example of an exception
n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Can't be divided by zero!")
OutputCan'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.")
OutputYou 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 Name | Description |
|---|
BaseException | The base class for all built-in exceptions. |
|---|
Exception | The base class for all non-exit exceptions. |
|---|
ArithmeticError | Base class for all errors related to arithmetic operations. |
|---|
ZeroDivisionError | Raised when a division or modulo operation is performed with zero as the divisor. |
|---|
OverflowError | Raised when a numerical operation exceeds the maximum limit of a data type. |
|---|
FloatingPointError | Raised when a floating-point operation fails. |
|---|
AssertionError | Raised when an assert statement fails. |
|---|
AttributeError | Raised when an attribute reference or assignment fails. |
|---|
IndexError | Raised when a sequence subscript is out of range. |
|---|
KeyError | Raised when a dictionary key is not found. |
|---|
MemoryError | Raised when an operation runs out of memory. |
|---|
NameError | Raised when a local or global name is not found. |
|---|
OSError | Raised when a system-related operation (like file I/O) fails. |
|---|
TypeError | Raised when an operation or function is applied to an object of inappropriate type. |
|---|
ValueError | Raised when a function receives an argument of the right type but inappropriate value. |
|---|
ImportError | Raised when an import statement has issues. |
|---|
ModuleNotFoundError | Raised 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!")
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.")
OutputError 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!")
OutputSomething 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)
OutputAge 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.
Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today
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
In Python, the help() function is a built-in function that provides information about modules, classes, functions, and modules. In this article, we will learn about help function in Python. help() function in Python SyntaxSyntax: help([object]) Parameters (Optional) : Any object for which we want so
6 min read
Python | __import__() function
While writing a code, there might be a need for some specific modules. So we import those modules by using a single-line code in Python. But what if the name of the module needed is known to us only during runtime? How can we import that module? One can use Python's inbuilt __import__() function. It
3 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
File Handling in Python
File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
6 min read
Reading and Writing to text files in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL
8 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
7 min read
Python Exception Handling
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. Example of Exception:Trying to
7 min read
User-defined Exceptions in Python with Examples
In Python, exceptions are used to handle errors that occur during the execution of a program. While Python provides many built-in exceptions, sometimes we may need to create our own exceptions to handle specific situations that are unique to application. These are called user-defined exceptions. To
4 min read
Python Built-in Exceptions
In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error. We can catch exceptions using try and
9 min read
Python Try Except
In Python, errors and exceptions can interrupt the execution of program. Python provides try and except blocks to handle situations like this. In case an error occurs in try-block, Python stops executing try block adn jumps to exception block. These blocks let you handle the errors without crashing
6 min read
Python RegEx
A Regular Expression or RegEx is a special sequence of characters that uses a search pattern to find a string or set of strings. It can detect the presence or absence of a text by matching it with a particular pattern and also can split a pattern into one or more sub-patterns. Regex Module in Python
15+ min read