Python Try Except

In this article, we will cover python try except and finally statement with the help of code examples.

Exceptions in Python

When your program detects an error, Python raises a number of exceptions (something in the program goes wrong). When certain exceptions occur, the Python interpreter terminates the current process and sends the control to the caller process until the exception is handled. If this is not done, the program will crash.

Consider the following program: function A calls function B, which calls function C. If an exception occurs in function C but is not handled there, it is sent to B and subsequently to A.

If this condition is not met, an error message is shown and our application comes to a quick and unexpected end.

Catching Exceptions

Exceptions in Python are managed with a try statement.

  • The try clause contains the critical operation that might cause an exception.
  • The except clause contains the code that handles exceptions.

Once we’ve caught the exception, we may pick which procedures to do. Here’s an example.

# import module sys to get the type of exception
import sys

randomList = ['x', 0, 4]

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

Output:

The entry is x
<class 'ValueError'> occurred.
Next entry.

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

The entry is 4
The reciprocal of 4 is 0.25

In this program, we loop through the randomList list’s values. As previously stated, the section that might create an exception is contained within the try block. If no exceptions occur, the except block is skipped and normal flow resumes (for the last value). However, if an exception occurs, it is handled by the except block (first and second values).

Using the exc_info() function from the sys module, we output the name of the exception. We can see that results in a ValueError and 0 in a ZeroDivisionError.

Since every exception in Python inherits from the base Exception class, we can also perform the above task in the following way:

# import module sys to get the type of exception
import sys

randomList = ['x', 0, 4]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print(e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

This program has the same output as the above program.

Catching Specific Exceptions in Python

In the above example, no specific exception was mentioned in the except clause. This is a bad programming technique since it will catch all exceptions and treat each instance in the same manner. We may tell an except clause which exceptions to catch.

A try clause can contain an unlimited number of except clauses to handle various exceptions, but only one will be performed if an exception occurs.

In an except clause, we may declare several exceptions by using a tuple of values. Here’s some pseudo-code to get you started.

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 errors occur during runtime. We may also raise exceptions manually by using the raise keyword.

We may optionally give values to the exception to explain why it was raised.

>>> 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:
...     x = int(input("Enter a positive integer: "))
...     if x <= 0:
...         raise ValueError("That is not a positive number!")
... except ValueError as y:
...     print(y)
...    
Enter a positive integer: -2
That is not a positive number!

Python Try Except Else Clause

In some cases, you may wish to run a specific bit of code if the code block inside attempts is completed without problems. You can utilize the optional else keyword with the try statement in these circumstances.

Note: Exceptions in the else clause are not handled by the preceding except clauses.

Example:

# 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:

When we enter an odd number

Enter a number: 3
Not an even number!

When we enter an even number

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

Python Try Except Finally

In Python, the try statement can include an optional finally clause. This clause is always performed and is typically used to release external resources.

For example, we may be linked to a faraway data center over the network, or we could be working with a file or a graphical user interface (GUI).

In all of these cases, we must clear away the resource before the program terminates, whether it ran properly or not. These activities (closing a file, launching a GUI, or disconnecting from a network) are carried out in the finally clause to ensure execution.

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

This type of construct makes sure that the file is closed even if an exception occurs during the program execution.

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. Python Write to File

Leave a Comment