This article aims to explore the utilization of try, except, and finally statements in Python, offering insightful examples on effectively managing exceptions.

 

In Python, there are two main types of problems: Syntax errors and Exceptions. Syntax errors happen because the code isn’t written correctly, while exceptions occur when unexpected things happen during the program, causing it to behave differently than usual.

 

There are four clauses commonly used to handle raised exceptions.

Explaining each clause
  1. try: An exception is caught in this block.
  2. except: Exceptions are handled in this block.
  3. else: The code inside it will execute when no errors are occurred.
  4. finally: Always executed no matter if an exception occurs or not.

Try and Except Statement – Catching Exceptions

In Python, try and except statements are employed to capture and manage exceptions. Code that might cause exceptions is enclosed within the try block, while the code responsible for handling those exceptions resides within the except block.

 

For example:

				
					my_list = [45, 78, 71, -89, 99]

try:
    print(f"3rd element = {my_list[2]}")
    print(f"6th element = {my_list[5]}")
except:
    print("Some error occurred")
				
			

Output

3rd element = 71
Some error occurred

In the given instance, the code lines posing potential errors are enclosed within the try statement (specifically, the second print statement). Attempting to access the sixth element of the list within the second print statement triggers an exception due to the absence of this element. Consequently, the except statement catches this specific exception.

Handling specific exceptions

When we don’t specify the type of problem to handle in the except part, it catches any issue that happens in the try part. This might seem helpful, but it’s not a great practice because it can make the code less reliable.

 

From the above example, the corrected code would appear like this:

				
					my_list = [45, 78, 71, -89, 99]

try:
    print(f"3rd element = {my_list[2]}")
    print(f"6th element = {my_list[5]}")
except IndexError:
    print("Index does not exists")
				
			

A try statement can contain multiple except blocks to manage different types of exceptions. However, only one of these blocks gets executed when an exception occurs. For instance:

				
					my_list = [45, 78, 71, -89, 99]

try:
    print(my_list[0] / 0)
    print(f"3rd element = {my_list[2]}")
    print(f"6th element = {my_list[5]}")
except IndexError:
    print("Index does not exists")
except ZeroDivisionError:
    print("Cannot divide by zero")
				
			

In the earlier example, we crafted an array and attempted to divide the first element by zero, causing the ZeroDivisionError exception. This was managed by printing the message “Cannot divide by zero” in the shell. Now, if we try to access an element beyond the range, like my_list[5], it would raise an IndexError exception, handled by displaying “Index does not exsists” in the shell.

Try with Else Clause

In Python, you can include an else clause following the try-except block. This else block gets executed only if the try clause runs without raising any exceptions.

				
					try:
    num1 = int(input("Enter number 1 = "))
    num2 = int(input("Enter number 2 = "))
    result = num1 / num2
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print(f"Result = {result}")
				
			

Enter number 1 = 5
Enter number 2 = 2
Result = 2.5

————-

Enter number 1 = 5
Enter number 2 = 0
Cannot divide by zero

  1. The try block attempts to obtain two numbers from the user and perform a division operation num1 / num2.
  2. If a ZeroDivisionError occurs during the division (if num2 is input as zero), it triggers the except ZeroDivisionError block and prints “Cannot divide by zero”.
  3. However, if the division operation within the try block is successful (i.e., no exceptions are raised), it moves to the else block.
  4. In the else block, it prints the result of the division as f"Result = {result}".

So, if the user enters valid non-zero numbers, it performs the division in the try block, enters the else block, and displays the result. But if the user inputs zero for num2, it triggers the except block and prints the specified message, avoiding the division by zero error.

Finally clause

In Python, the finally keyword ensures a block of code is always executed, regardless of whether the try block completes normally or encounters an exception. This block executes after the normal completion of the try block or after the try block terminates due to an exception.

 

Utilizing the finally clause in scenarios like file operations is a great practice. It ensures that essential cleanup operations, like closing a file to conserve resources, are executed consistently, regardless of whether the preceding code runs smoothly or encounters exceptions. This helps maintain a clean and efficient code structure.

				
					try:
    num1 = int(input("Enter number 1 = "))
    num2 = int(input("Enter number 2 = "))
    result = num1 / num2
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This is always executed")
				
			

Enter number 1 = 10
Enter number 2 = 5
2.0
This is always executed

————-

Enter number 1 = 10
Enter number 2 = 0
Cannot divide by zero
This is always executed

The finally clause acts as a failsafe, ensuring that essential operations are carried out regardless of the circumstances within the preceding code block. It’s incredibly useful when you have critical functions or operations that must be executed, ensuring they run even if exceptions occur.

Leave a Reply

Your email address will not be published. Required fields are marked *

Welcome to our diverse learning options!

Select the learning format that suits your preferences and schedule.