Mastering Advanced Python Concepts

Try-Except Block in Python (Using with Examples)

Try-Except Block in Python (Using with Examples)

Introduction

With the aid of examples, you will learn how to use the try, except, and finally statements to manage errors in your Python script in this article.

Many built-in exceptions in Python are thrown when a problem is encountered by your application (something in the programme goes wrong). The Python interpreter pauses the running process and gives control to the caller process until these exceptions are addressed. The software will crash if it is not addressed. Consider a software where function A calls function B, and function B calls function C. An exception that happens in function C but isn't handled there is sent to B before being handled by A. If the mistake is never addressed, a notification is shown and our software abruptly and unexpectedly stops.

Catching Exceptions in Python

A try statement in Python can be used to manage exceptions. The try clause contains the crucial operation that can cause an exception. The except clause contains the code that manages exceptions. Thus, after we have identified the exception, we may decide what actions to take. Here is an easy illustration.

import sys

randomList = ['a', 0, 2]
for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
 

Output

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5

We cycle over the values in the randomList list in this application. The try block contains the code that, as was discussed earlier, might lead to an exception. The unless block is bypassed and regular flow resumes if there is no exception (for last value). But the unless block handles any exceptions that do arise (1st and 2nd values). Here, we use the exc info() method in the sys module to output the name of the exception. As we can see, a results in ValueError whereas 0 results in ZeroDivisionError. We may alternatively complete the aforementioned work in the following manner because every exception in

Python derives from the basic Exception class:

import sys
randomList = ['a', 0, 2]
for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

The output from this script is identical to that of the one above.

Handling Specific Exceptions

The except clause in the aforementioned example lacked any specific exceptions. This is an inappropriate programming style since it will handle every error and circumstance equally. An except clause can specify which exceptions it should cover. A try clause may include as many except clauses as necessary to address the possible exceptions, but only one of them will be implemented in the event of an exception. A tuple of values can be used to specify several exceptions in an except clause. This is an example of pseudocode.

try:
  # do something
  pass

except ValueError:
  # handle ValueError exception
  pass

except (TypeError, ZeroDivisionError):
  # handle multiple exceptions
  # TypeError and ZeroDivisionError
  pass

except:
  # handle all other exceptions
  pass

Raising Exceptions in Python

Exceptions are produced in Python programming when runtime issues happen. Using the raise keyword, we can manually raise exceptions as well. If we want to know why an exception was raised, we may optionally give data to the exception.

raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt

raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument

try:
...    a = int(input("Enter a positive integer: "))
...    if a <= 0:
...        raise ValueError("That is not a positive number!")
... except ValueError as ve:
...    print(ve)
...   
Enter a positive integer: -2
That is not a positive number!

Try with else clause

If the code block within the attempt executed without any issues, you could occasionally wish to run another section of code. You can pair the try statement with the optional else keyword in certain situations. Note: The preceding except clauses do not apply to exceptions in the else clause.

Let's examine an illustration:

# program to print the reciprocal of even numbers

try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print(reciprocal)


Output
If we pass an odd number:
Enter a number: 1
Not an even number!

If we pass an even number, the reciprocal is computed and displayed.

Enter a number: 4
0.25 

However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by preceding except.

Enter a number: 0
Traceback (most recent call last):
  File "<string>", line 7, in <module>
    reciprocal = 1/num
ZeroDivisionError: division by zero

Try...finally

In Python, a finally clause is an optional addition to the try statement. This phrase, which is typically used to release external resources, is always put into effect. For instance, we may be utilizing a file or a GUI while connecting through the network to a distant data center.

In either of these scenarios, whether the programme ran successfully or not, we must clear away the resource before it terminates. The finally clause carries out these operations (closing a file, shutting a GUI, or disconnecting from the network) to ensure execution. Here is a file operation example to demonstrate this.

try:
  f = open("test.txt",encoding = 'utf-8')
  # perform file operations
finally:
  f.close()

write your code here: Coding Playground

Even if an exception arises while the script is running, this kind of technique ensures that the file is closed.