Try Except in Python

An exception or error is an abnormal condition or problem that occurs during the execution of a program. If any error occurs during the program execution, the program terminates abnormally or unexpectedly and does not execute further.

This abrupt termination can lead to various consequences, such as data loss, software issues, or even system crashes. Therefore, it is essential to handle exceptions to prevent to prevent programs from terminating abruptly due to errors and neatly run the program successfully.

Handling an exception is an essential aspect of programming, ensuring that when our program encounters any issue, it will continue to execute and provide an informative message to the user or programmers about what went wrong. Hence, effective exception handling will make our program more robust and simplify the debugging process.

Python provides five essential keywords to handle an exception. They are as follows:

  • try
  • except
  • else
  • finally
  • raise

We can use these keywords to handle exceptions properly. In this tutorial, we will learn how to handle exception using try except block in Python, exploring various example programs to understand their practical implementation. Let’s get started!

Try Block in Python


A try block is a block of code or statements that might raise an exception during the program execution. That’s why we also call it as an exception-generated block. We place the code inside the try block that may generate an exception during the execution of the program.

In other words, we should keep the exception generated code (i.e. risky code) within the try block. We should not place the normal code inside try block. Let’s understand it with the help of an example.

Consider that there are three statements inside try block. Out of three statements, there may occur exception in the first statement and is on top within try block. The other two statements are normal and are below the first statement.

In this situation, if an exception occurs in the first statement, the other two normal statements will not execute. So, we should place the other two statements outside the try block so that the length of code inside the try block should be as much as less.

Except Block in Python


A except block in Python is a block of code that is responsible for catching and handling the exception raised within the corresponding “try” block.

That’s why we also call it as an exception handler block because its purpose is to handle specific types of exceptions that may occur during the execution of the try block. A except block that catches an exception must be followed by a try block that generates an exception.

Syntax of Try Except in Python


The general syntax or structure of try-except block in Python for handling an exception is as follows:

try:
   # A block of code that may generate an exception
except ExceptionType:
   # Code to handle the exception when raised

In the above syntax, ExceptionType represents a specific type of exception class or subclass that catches and handles within the except block. Both try and except are keywords in Python. The try block contains the code that might raise an exception, while the except block is where specific exceptions are caught and handled.

The below example demonstrates the fundamental use of ‘try except’ block in Python:

try:
    result = 10 / 0  # Division by zero triggers an exception
except ZeroDivisionError:
    print("Division by zero is not allowed.")
Output:
      Division by zero is not allowed.

Possible Combination of Try-Except Block


Every try block is associated with one or more except blocks. However, we can combine it with various other blocks to handle exceptions effectively. The four possible forms of try block are as follows:

(1) try-except: A try block is always followed by one or more except blocks.

(2) try-except-else: A try block is followed by except block and else block allows that code if no exceptions occur within the try block.

(3) try-finally: A try block followed by a finally block that always gets executed whether the program throws an exception or not.

(4) try-except-finally: A try block followed by one or more except blocks followed by a finally block.

Exception Handling Mechanism using Try Except Block


A systematic representation of the relation between try-except block in Python has shown in the below figure.


Python try except block

When an exception occurs within the try block, the Python interpreter immediately stops further execution of code inside the try block and transfers the control of execution from the try block to the corresponding except block that handles the exception thrown by the try block.

Python searches for a matching except block in the program code that can catch and handle the specific type of exception raised. Except block follows the try block, acts as an exception handler that is used to catch and handle the exceptions.

Each except block is associated with a specific type of exception. Python interpreter compares the type of raised exception to the type specified in the except block or clause to find a match.

If a matching except block is found for the exception raised, the exception is handled and the code or statements within that except block are executed. This code is responsible for handling the exception and displaying for an appropriate error message or a user-generated message.

If the runtime system cannot find an appropriate exception handler after looking for all the relevant blocks in the program, the execution of the program stops. In this situation, Python generates a message through its default exception handler, indicating that the specific exception wasn’t handled, resulting in the program termination.

In case no exception is thrown by the try block, the except block is ignored and the control of execution is passed to the next statement after the except block.

Control Flow of Try Except Block


Consider the below example code in which we will understand the control flow inside the try-except block in Python.

try:
    statement1
    statement2
    statement3
except ExceptionType:
    statement4

# Outside the try-except block.    
statement5

In the above code, there are three statements inside the try block, one statement inside except block, and one statement outside try-except block. Let’s understand the following cases.

Case 1:

Suppose no exception occurs inside try block, statement1, statement2, and statement3 will execute normally. However, in this case, the except block won’t execute because no exception is thrown by the try block. The code inside the except block only runs when an exception is raised and caught by a corresponding except block.

After the complete execution of try block, the control of execution will transfer to the next statement outside the try-except block. Now, statement5 will execute normally. Let’s take an example based on it.

Example 1:

try:
    print("Before divide") # statement1
    result = 10 / 2  # This won't raise any exception # statement2
    print("After divide") # statement3
except ZeroDivisionError:
    print("Error: Division by zero occurred") # statement4

# Outside the try-except block.
print("Outside the try-except block") # statement5
Output:
       Before divide
       After divide
       Outside the try-except block

In this code, the statement “result = 10 / 2” won’t raise a ZeroDivisionError exception, so the except block won’t execute. Instead, the code within the try block will execute normally, and the program will continue further execution after the except block.

Case 2:

Suppose an exception occurs in statement2 inside try block and a matching except block is found for the exception raised. What will be the control flow in this case?

a) Inside try block, statement1 will execute normally.

b) When an exception raised in statement2, the control of execution immediately is transferred to except block and statement4 inside the except block will execute.

c) After the execution of statement4, statement3 in try block will not execute because the control never goes back to execute the remaining code inside the try block.

d) After the complete execution of except block, statement5 will execute normally.

Example 2:

try:
    print("Before divide") # statement1
  # This statement will raise an exception in the try block.
    result = 10 / 0  # statement2
    print("After divide") # statement3

except ZeroDivisionError:
    print("Error: Division by zero occurred") # statement4

# Outside the try-except block.
print("Outside the try-except block") # statement5
Output:
       Before divide
       Error: Division by zero occurred
       Outside the try-except block

Case 3:

Suppose an exception occurred at statement2 and no matching except block is found to handle that specific type of exception. In this case, what will be the control flow?

a) The statement1 will execute normally within the try block.

b) If an exception occurred in statement2 and no matching except block is found to handle that specific type of exception, the program will terminate with an unhandled exception error. In this case, the rest of code will not execute outside the try-except block. Let’s understand it with an example code.

Example 3:

try:
    print("Before divide") # statement1
  # This statement will raise an exception in the try block.
    result = 10 / 0  # statement2
    print("After divide") # statement3

except ValueError:
    print("Error: Division by zero occurred") # statement4

# Outside the try-except block.
print("Outside the try-except block") # statement5
Output:
       Before divide
       ZeroDivisionError: division by zero

As you can see in the above code, statement4 and statement5 have not executed due to not matching except block found for the exception raised in the try block.

Case 4:

Suppose an exception occurred in the statement4 inside the except block. In this case, what will be control flow?

Note that an exception occurs not only inside the try block but also can occur inside except block and finally block. Since the exception has occurred inside the except block and the statement is not inside the try block, the except block will not execute. The program control will be transferred to the statement5 for the execution.

Example 4:

try:
    print("Before divide") # statement1
    print("After divide") # statement2

except ZeroDivisionError:
    # This statement will raise an exception in the except block.
    result = 10 / 0  # statement3

# Outside the try-except block.
print("Outside the try-except block") # statement4
Output:
       Before divide
       After divide
       Outside the try-except block

Case 5:

Suppose an exception occurs in statement5. In this case, what will be control flow?

Since statement 5 is not inside try block, the execution of the program will terminate abnormally. In this case, statement1, statement2, and statement3 inside the try block will normally execute. Since an exception is not found inside the try block, the except block will not execute.

Example 5:

try:
    print("statement 1")
    print("statement 2")
    print("statement 3")

except Exception:
    print("statement 4")

# This statement will raise an exception in the except block.
result = 10 / 0 # statement5
Output:
        statement 1
        statement 2
        statement 3
        ZeroDivisionError: division by zero

Exception Handling using Try-Except Block in Python


Let’s take some simple example programs based on exception handling using try except block in Python.

Example 6:

print("111")
print("Before divide")
x = 20 / 0 # Exception occurred
print("After divide")
print("222")
Output:
       111
       Before divide
       ZeroDivisionError: division by zero

As you can see in this example code, the rest of the code is not executed and the execution of program is terminated abnormally due to the generation of ZeroDivisionError at line int x = 20 / 0.

Suppose that there are 100 lines of code in the program after exception raised. Then, all the code after exception will not execute. To overcome it, we will use try-except block to handle the exception in Python. So, let’s see how?

Example 7:

def func():
    print("111")
    print("Before divide")

  # Applying try-except block to handle exception.
    try:
        x = 1 / 0
        print("After divide")
    except(ZeroDivisionError):
        print("A number cannot be divided by zero")

# Calling function
func()
print("222")
Output:
       111
       Before divide
       A number cannot be divided by zero
       222

As you can observe in the above code, we have properly handled the exception raised using try except block and the rest of the code also executes.

Advanced Example Programs on Try-Except Block


Let’s take some advanced example programs for the best practices based on exception handling using try-except block with a brief explanation.

Example 8:

def funct():
    print("111")
    try:
        x = 12 / 0 # exception occurred
        print("Result of x: ", x)
        print("222")
    except(ZeroDivisionError):
        print("Hello world")

funct()
print("333")
Output:
       111
       Hello world
       333

In the preceding code, an exception has occurred in the first line inside try block. Since the matching except block is found, the program control immediately is transferred to the except block without executing the rest of the code inside the try block. Inside the except block, the statement is executed normally.

Example 9:

x = 30
y = 0
def divide():
    print("I am in method")
    try:
        print("I am in try block")
        z = x / y
        print("Result of z: ", z)

    except(ValueError):
        print("I am in except block")

print("I am outside the method")
divide()
Output:
        I am outside the method
        I am in method
        I am in try block
        ZeroDivisionError: division by zero

In the above code, no matching except block is found for the exception raised inside the try block. Therefore, the exception is not handled by except block, and the program execution is terminated abnormally.

Example 10:

try:
    print("111")
    print("222")
except(Exception):
    print("333")
print("444")
Output:
        111
        222
        444

In this example, no exception occurred in the try block. Therefore, the program control will not transfer to the except block to execute the statement.

Example 11:

def funct():
    print("One")
    try:
        print("Two")
        y = 1/0
    except(ZeroDivisionError):
        try:
            print("Three")
            x = 20/0
        except(ValueError):
            print("Four")

print("Five")
funct()
Output:
       ZeroDivisionError: division by zero
       Five
       One
       Two
       Three

Example 12:

def funct():
    print("One")
    try:
        print("Two")
        y = 1/0
        print("Three")
    except(ZeroDivisionError):
        try:
            print("Four")
        except(Exception):
            x = 20 / 0
            print("Five")
funct()
print("Six")
Output:
       One
       Two
       Four
       Six

In this tutorial, we have covered almost all important points related to try except block in Python with the help of various example programs. Hope that you will have understood how to handle exception using try-except block. Stay tuned with the next tutorial where we will learn how to handle multiple exceptions in Python.
Thanks for reading!!!