Python Try Except Blocks

Python Try Except Blocks

posted 10 min read

After getting a detailed explanation of exception handling, the next question that comes to your mind is how you can achieve exception handling in your software program. Python has provided us with a very defined structured approach related to exception handling, i.e. Try-Except block. In this tutorial, I will cover the overview of the try-except statement, the workflow of try and except block, and a way to handle the exception with the help of different examples.

Try and Except Statement in Python: An Overview

In Python, the try and except statement is the core concept that deals with incoming errors. The Python developers implement the try and except block to catch the potential errors that the program might encounter and take the correct measures on time before the application crashes. When you are working on a Python program, the piece of code having the potential risk of encountering an error will be put inside the try block later on, except block is implemented to respond to the related exception.

Try Block: Definition

When you use the try block in your program, the compiler will test the code throughout the execution. The code inside this block will run until an error is encountered or else gives the output.

Syntax for Try Block

 
 
try:  
#code that needs to be tested and can cause an exception  
pass  
 

Except Block: Definition

Except block is used to respond to the exceptions coming in try block and deal with them. When the exception is encountered in a try block, the compiler jumps to the except block where the solution code is provided. You define the except block in such a way that it will catch the error and handle it. Also, you can define as many except blocks as you need in the program.

Syntax for Except Block

 
 
try:  
#code that needs to be tested and can cause an exception  
pass  

except exception1:  
#code to handle the exception1  
pass
  
except exception2:  
#code to handle the exception2  
pass  

except exceptionN:  
#code to handle the exceptionN  
pass 
 
Note: Remember, you can use multiple except blocks with a single try block.

How does the Try-Except statement work?

As illustrated in the flow diagram, suppose you write a simple Python program where you are adding two numbers. You take the number from the user where the user enters "a" instead of number. During coding, you add this piece of code inside the try block to handle if an error comes beforehand. Now, the compiler executes the program and takes the number from the user to perform addition but gets an error instead. Therefore, the compiler stops the execution, tries to resolve the exception first, and jumps to the except block that handles the exception. Here, a typeerror exception occurs. If there is no error in the try block, the else block will print the result. It ensures no error in the try block code because this block will only run when no exception is present.

Note: You can use the try block without using the except block, but this is not a good approach and only be used when you don't want to address the exception at that time

Code Demonstration: Try-Except Block

There are many ways of using try and except blocks for exception handling implementation in your Python program.

Catching All Exception

  • If you want to catch all the exceptions without specifying the exception name, then the generic exception approach is used. This can be achieved by using the keyword, except without defining the exception type. The compiler will catch all types of errors whenever it encounters the try block.
  • This approach is helpful when you want to catch all the exceptions without generically specifying the name and saves your application from abrupt stopping from unhandled exceptions.
Caution: In my opinion, always try to avoid using the catch-all exception approach as it will also try to catch the debugging-related issues and hinder the code execution

Code for Catching All Exceptions

def addition(num1, num2): #addition function 
    try: 
        num3 = num1 + num2 #this line will raise exception 
    except Exception as e: 
        print("An Exception occur") #here the exception is handled
        print(type(e)) #prints the type of error with name
        return None 
    else: 
        return num3 
result = addition("8", 0) 
print("Addition of two numbers:" , result) 

In the above code, I define the addition function that takes two numbers as an argument and performs the addition operation. The variable num3 will store the result. I put the add operation and its result in the try block that raises the exception. After that, I write the except block with the base class Exception that catches all the exceptions in the code and stores it in the variable e. The type(e) will print the exception class with its name. To check, call the addition function and pass two values, one as string and the second as int, which raises the type error you can see in the output.

Tip: Try to use except Exception as e to get the details of the error

Output

Catching Specific Exception

  • The other way to catch the exceptions is by specifying the exception name. This approach will help you handle the exception precisely and improve the program's robustness.
  • This approach also ensures clarity in the program, as the handling code for each exception is defined separately.

Code for Catching Specific Exception

def addition(num1, num2): 
    try: 
        num3 #here we are defining num3
        num = num1 + num2  #instead of using num3 we are using num that raises the exception
    except NameError: #catche the except and handles it
        print("Name Error: Your are trying to use undefined variable") 
        return None 
    else: 
        return num3 
result = addition(8, 0) 
print("Addition of two numbers:" , result) 

In the above code snippets, I defined the name of the exception as NameError in the except block. When I am using the num variable for storing the result, the variable num3 is undefined, which raises the error related to this exception. So, the compiler jumps to the except block and executes the code implemented here. You can also mention as many exceptions as possible that you think will be encountered.

Output

Using the Try Except Block with Functions

You can also use the try and except block inside the function, as I defined in the example of a simple calculator program at the coding part.

Code: Using Functions

print("SIMPLE CALCULATOR") 
print("Having operation '-', '*' and '/'") 
def subtraction(num1, num2): #function for subtraction 
    try: 
        num3 = num1 - num2 #this line will give an exception if values are incorrect type 
        return num3 
    except TypeError: #here on getting exception compiler jumps into this part and executes the code   
        print("Error: you are giving string instead of integer number in Subtract Function") 
        return None 
def multiplication(num1, num2): #function for multiplication 
    return num1 * num2 
def division(num1, num2): #function for division 
    try: 
        num3 = num1 / num2 #this line will give exception if num2 values is zero 
        return num3 
    except ZeroDivisionError: #if this exception occurs then the compiler jumps at this part  
        print("Error: you try to divide the number with 0")  
        return None 
result1 = subtraction("10", 5) 
result2 = multiplication(5, 5) 
result3 = division(8, 0) 
print("Subtraction of two numbers:" , result1) 
print("Multiplication of two numbers:" , result2) 
print("Division of two numbers:" , result3) 

In the above program, I first create three functions related to each math operation. Each function will take two numbers as an argument and return the calculation to the result variable that prints the output. Here, I am using multiple try and except blocks for each function. Firstly, in the subtraction(num1, num2) function, the TypeError exception is handled in the except block. Also, in the division(num1, num2) function, I passed the values 8 and 0. As we know, the number cannot be divided by zero in practical math calculation, so as in programming, it creates the error by stopping the program abruptly. Therefore, except block is used to handle the ZeroDivisionError exception.

Tip: In the try block, only add that piece of code that will raise the exception instead of adding all the code and trying to minimize the code of the try block

Output

Propagate Exception

When you are working with the try-except block with a function, there is a situation needed when you call the function into another function at that time. If the calling function causes an exception and is not handled at the function definition, then the stack will propagate to the top part where it is handled. Let's take an example of a division function.

Code: Implementing Propagating Exceptions

print("SIMPLE CALCULATOR") 
def division(num1, num2): #function for division 
        num3 = num1 / num2 #this line will give exception if num2 values is zero 
        return num3 
def calculation(num1, num2): 
    try: 
        result = division(num1,num2) #division function is call and stores the result 
        print("The Result of division of two numbers" , result) 
    except ZeroDivisionError: #if this exception occurs then the compiler jumps at this part  
        print("Error: you try to divide the number with 0")  
        return None 
    print("calculation is done") 
calculation(8, 2) 
calculation(6,0) 
print("End") 

As depicted in the code, I created two functions named division(num1, num2) and calculation(num1,num2). The division(num1, num2) function will take the two variables to perform the division operation, store the result in the variable num3, and return it. After that, the calculation(num1 ,num2) function is defined which calls the division(num1,num2) function and stores its result. When you pass the values to the calculation(num1, num2) function, it will jump to the division function for division operation, but if the num2 is zero that will raise the exception. The exception is not handled there, so the compiler propagates to the calculation function where it is handled.

Output

FAQs Q: Can I use try and except block within try and except block?
A: Yes, there is a concept of nested try-and-except block in Python through which you can define the nested try-except block in your program
Q: Is it possible to catch all the exceptions?
A: Yes, if you want to catch all the exceptions at once then the approach of using the except keyword without specifying the name is essential because it will catch all the exception that comes in the program.
Q: What is the use of the else block?
A: Using the else block within your program is a very good approach as it helps you to make sure that there are no exception encounters in your program.

Wrapping Up

In conclusion, try and except block is the fundamental topic of every programming language. It is the need for software programs because every programmer wants to write code that would be efficient and run smoothly. These try and except blocks ensure that the program deals with the error gracefully and doesn't perform the abnormal execution. As we know, it is impossible to find all the future errors beforehand, but with exception handling, you can prepare your program for future exceptions to some extent. Now, I hope it will be easy for you to use exception handling with try and except statements in your code. Thanks for reading the guide. Happy Coding!


Reference

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Python Finally Block

Abdul Daim - Mar 7

Python Opening & Reading Files

Abdul Daim - Mar 8

Python Exception Handling

Abdul Daim - Mar 4

Setting up Virtual Environment in Python

Tejas Vaij - Apr 20

Mastering Data Visualization with Matplotlib in Python

Muzzamil Abbas - Apr 18
chevron_left