Python Try Except 

Python Try Except 

5 mins read190 Views Comment
Updated on Feb 9, 2023 16:49 IST

This article is revolving around Python Try Except where Exception Handling in Python and different types of exceptions like raise and assert is also covered.

2023_01_MicrosoftTeams-image-18.jpg

Python provides a variety of tools for handling unexpected events or exceptions.  

Today, we will discuss Python exceptions and how to handle them using the try-except block, the raise statement, and the assert statement. So, without further ado, let’s get started. 

We will be covering the following sections: 

What are Exceptions in Python? 

A Python exception is an event that occurs during program execution and interrupts the normal flow of commands. If an exception occurs, the Python interpreter generates an exception object that contains information about the Exception, such as the type of Exception and the location where the Exception occurred. 

Some examples of exceptions that can occur in Python include: 

  • IOError: raised when a file cannot be opened or a network connection cannot be established 
  • ValueError: raised when a value passed to a function or method is not of the expected type or out of range of the valid input 
  • TypeError: raised when an operation or function is applied to an object of an inappropriate type 
  • KeyError: raised when a key is not found in a dictionary 
  • IndexError: raised when an index is out of range 
  • ZeroDivisionError: raised when an attempt is made to divide a number by zero 

Python provides a rich set of built-in exceptions that you can use to handle exceptional cases that may occur in your code. You can also define your custom exceptions by creating a new class that inherits from the Exception class. 

What are the Top 10 Python Applications in Real-World?
What are the Top 10 Python Applications in Real-World?
Here we will discuss the Top 10 Python Applications. So, without further ado, let’s get started.
Object-Oriented Programming with Python
Object-Oriented Programming with Python
A good understanding of OOPs concepts can help you make your Python programming journey smoother. In this article, we will explore the basics of object-oriented programming in Python.
Top 10 Python Books for Beginners to Experienced Programmers
Top 10 Python Books for Beginners to Experienced Programmers
Want to get started with Python programming language? Each Python book in this list encapsulates real-world examples and exercises, making Python's journey engaging and accessible. Choose your learning adventure and...read more

Related: Python interview questions

Exception Handling in Python 

Exception handling in Python is the process of dealing with exceptional cases or unexpected events that may occur during the execution of a Python program. An exceptional case, or Exception, is an event that disrupts the normal flow of instructions in a program. Examples of exceptions include a file not found, a divide-by-zero error, or an invalid input from a user. 

When an exception occurs, Python generates an exception object that contains information about the Exception, such as the type of Exception and the location where the Exception occurred. The Python interpreter then looks for a block of code that is specifically designed to handle the Exception. This code block is called an exception handler and is typically defined using a try-except block. The try block contains the code that might raise the Exception, and the except block contains the code that will handle the Exception. 

Python Try Except Block 

Python’s try-except block is a powerful tool for handling exceptions, or unexpected events, in your code. Exceptions are events that occur during the execution of a program that disrupts the normal flow of instructions. When an exception occurs, it can cause the program to terminate abruptly, which can lead to data loss or other undesirable consequences. The try-except block allows you to handle exceptions in a controlled manner, so your program can continue to execute even in the event of an exception. 

The basic syntax of a try-except block is as follows: 

 
try:
# code that might raise an exception
except ExceptionType:
# code to handle the exception
Copy code

The code that might raise an exception is placed in the try block, and the code to handle the Exception is placed in the except block. The ExceptionType is the type of Exception that you want to handle. For example, if you want to handle a ValueError exception, you will write: 

 
try:
# code that might raise a ValueError
except ValueError:
# code to handle the ValueError
Copy code

In the except block, you can take the appropriate action to correct the problem and then continue with the program’s execution.  

You can also specify multiple exception types in the same except block by providing a tuple of exception types. For example:  

 
try:
# code that might raise a ValueError or an IOError
except (ValueError, IOError):
Copy code

You can also use a wildcard (Exception) to catch all possible exceptions. 

 
try:
# code that might raise any exception
except Exception:
# code to handle any exception
Copy code

You can also use as the keyword to assign the exception object to a variable, which you can then use in your exception-handling code. For example: 

 
try:
# code that might raise an exception
except ValueError as e:
print("A ValueError occurred:", e)
Copy code

You can also use the finally block to put some code that will be executed whether the Exception occurred or not. 

 
try:
# code that might raise an exception
except ValueError as e:
print("A ValueError occurred:", e)
finally:
# some code to cleanup or do something else
Copy code

Raise Exception 

You can also use the raise statement to raise the Exception again if you can’t handle it, or you can use the assert statement, which raises an exception if the condition isn’t met. The raise statement allows you to explicitly raise an exception, which can be helpful in situations where you want to signal that an error has occurred.  

For example, you might use the raise statement to signal that a function has been passed an invalid argument: 

 
def divide(a, b):
if b == 0:
raise ZeroDivisionError("division by zero")
return a / b
Copy code

In this example, the divide() function raises a ZeroDivisionError exception if the value of the b argument equals zero. This allows the caller of the function to handle the Exception appropriately. 

You can also use the raise statement with the from keyword to specify the original Exception. For example: 

 
try:
value = int("foo")
except ValueError as e:
raise ValueError("Invalid value") from e
Copy code

This will raise a new ValueError with the message “Invalid value” and also attach the original exception e, which is a ValueError with a message “invalid literal for int() with base 10: ‘foo'”, This way, the exception traceback will include both the original and new Exception. 

Assert Exception 

It is also essential to be aware of the assert statement, which allows you to test for a condition and raise an exception if the condition is false. The assert statement is a convenient way to insert debugging assertions into your code, as it will raise an exception if the condition is not met. 

 
assert value > 0, "value must be positive"
Copy code

In the above example, if a value is not greater than zero, an AssertionError exception will be raised with the message “value must be positive.” 

Endnotes 

In conclusion, Python allows Exception handling in multiple ways. The few tools we have discussed in this article are: 

  • The try-except block: allows you to handle exceptions in a controlled manner 
  • The raise statement: allows you to raise exceptions explicitly 

The assert statement: allows you to test for conditions and raise exceptions if the conditions are not met.  

All these tools provide a way to deal with exceptional cases that may arise during the execution of a Python program. Want to learn more about Python and practice Python programming? Explore related articles here

Contributed by-Prerna Singh

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio