Python Try Except: The Complete Guide

An exception is an error that happens during the execution of a program. When that error occurs, Python generates an exception that can be handled, preventing your program from crashing.

Exceptions are a convenient way of handling errors and particular conditions in the program. You should use an exception handling mechanism if you think you have a code that can produce an error.

What are the exceptions in Python?

Python has many built-in exceptions that force your program to output an error when something in it goes wrong. 

When these exceptions occur in the program, it causes the current process to stop and passes it to a calling process until it is appropriately handled.

If the python exceptions are not handled, then our python program will crash.

Raising an Exception in Python

We can use the raise to throw an exception if the condition occurs.

The statement can be complemented with the custom exception.

If you want to throw the error when a particular condition occurs using raise, you can write the code below.

# app.py

el = 11
if el > 10:
    raise Exception('el should not exceed 10. The value of x was: {}'.format(x))

See the output.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 3, in 
    raise Exception('el should not exceed 10. The value of x was: {}'.format(x))
NameError: name 'x' is not defined
➜  pyt

The execution comes to a halt and displays our exception to screen, offering clues about what went wrong.

An AssertionError Exception

Instead of waiting for the program to crash in the midway, you can also start by making the assertion in Python.

We assert that the specific condition is met.

If the condition turns out to be true, then it is excellent! The program can continue.

If the condition turns out False, you can have the program throw the AssertionError exception.

See the following code.

# app.py

import sys

assert ('linux' in sys.platform), "This piece of code runs on Linux only."

If you run this code on the Linux machine, the assertion passes.

If you are running this code on a Windows machine or Mac like me, the outcome of an assertion would be False, and the result would be the following.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 3, in 
    assert ('linux' in sys.platform), "This piece of code runs on Linux only."
AssertionError: This piece of code runs on Linux only.
➜  pyt

Python try-except

The try block lets you test the block of code for possible errors. In Python language, exceptions can be handled using the try statement.

The critical operation which can raise the exception is placed inside the try clause, and the code that handles an exception is written in except clause.

The except block lets you handle an error. The finally block, you execute code, regardless of the result of the try-except blocks.

When the error occurs, or exception, Python stops executing the program and generates an error message.

Let us see a simple example.

# app.py

try:
    print(k)
except:
    print('One error has been thrown')

In the above code, we have not defined the k variable so the try block raises an error, and the except block will be executed, and we see the output in the console.

Python Try Except Example | Exception Handling in Python

If we do not write the try-except block, the python program will crash and raise an error. See the following example.

# app.py

print(k)

Exception Handling in Python

Exception Handling in Python

If we use exception handling in Python, we first need to have a catch-all except clause. The words ‘try’ and ‘except’ are Python keywords that catch exceptions.

The syntax is the following.

try:
    some statements here
except:
    exception handling code here

See the following example.

# app.py

try:
    print(21/0)

except ZeroDivisionError:
    print ('You can\'t divide anything by zero, Exception Found')

So, here the try block raises an exception, and except block catch that exception and runs the code of except block, which is to print the message in the console.

try-except else clause in Python

The else clause in the try-except statement must follow all the except clauses, and it is useful for the code that must be executed if the try clause does not raise an exception.

try:
     operation_that_can_throw_ioerror()
except IOError:
     handle_the_exception_somehow()
else:
     # we don't want to catch the IOError if it's raised
     another_operation_that_can_throw_ioerror()
finally:
     something_we_always_need_to_do()

try-finally clause in Python

Let’s take a scenario where you always had to implement some action to clean up after executing the code.

Python enables you to do so using the finally clause.

If the finally block is specified, it will be implemented regardless of whether the try block raises an error or not.

# app.py

try:
    print(21/0)

except ZeroDivisionError:
    print ('You can\'t divide anything by zero, Exception Found')

finally:
    print('finally block is executed')

try-finally clause in Python

try-except finally in Python

See the following code.

# app.py

import sys


def linux_check():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')


try:
    linux_check()
except AssertionError as error:
    print(error)
else:
    try:
        with open('error.log') as file:
            read_data = f.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('It will print irrespective of any exceptions.')

You will get the following output if executing this code on the Linux machine.

Doing something.
[Errno 2] No such file or directory: 'error.log'

From the output, you can see that the linux_check() function ran because no exceptions were encountered, and then an attempt to open error.log was made.

The error.log file does not exist, and instead of opening a file, you caught a FileNotFoundError exception.

Otherwise, like me on mac or windows, you will get the following result.

➜  pyt python3 app.py
Function can only run on Linux systems.
It will print irrespective of any exceptions.
➜  pyt

In the previous code, everything in the final clause will be executed.

It does not matter if you encounter the exception somewhere in the try or else clauses.

List of Exception Errors :

  1. IOError: If the file can’t be opened.
  2. KeyboardInterrupt: When the user presses an unrequired key.
  3. ValueError: When the built-in function receives the wrong argument.
  4. EOFError: If the End-Of-File is hit without reading any of the data.
  5. ImportError: If it is unable to find a module.

You can find more about Exception Handling on python’s official docs.

Key points 

  1. The try clause is executed up until the point where the first exception is encountered.
  2. Inside the except clause or the exception handler, you determine how a program responds to the exception.
  3. You can anticipate multiple exceptions and differentiate how the program should respond to them.
  4. Avoid using bare except clauses. The reason is the catching Exception hides all errors…even those that are entirely unexpected. That is why you should avoid bare except clauses in your Python programs. Instead, you’ll want to refer to particular exception classes you want to catch and handle.

Conclusion

You have learned about various ways to raise, catch, and handle exceptions in Python. Let’s refresh what we have learned.

  1. The raise allows you to throw an exception at any time.
  2. An assert enables us to verify if a certain condition is met and throw the exception if it isn’t.
  3. In the try clause, all statements are executed until the exception is encountered.
  4. The except is used to catch and handle the exception(s) encountered in a try clause.
  5. The else lets you code sections that should run only when no exceptions are encountered in the try clause.
  6. finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.

That’s it for this tutorial.

Recommended Posts

Python recursion

Python operators

Python Not Equal Operator

Python property

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.