Home » Programming » Python » Python Catch Errors Try Except

Catch Errors/Exceptions in Python with try/except [Examples]

This article will show you how to use the try/except/finally statements.

What are Errors/Exceptions

A computer program will produce an error, also known as an exception, when something goes wrong.

This could be due to mistyped programming commands (syntax errors) or because the application encountered something unexpected – be it bad user input or a logical condition that can’t be met.

When something goes wrong, an exception/error will be thrown – which will usually result in the application stopping and the error being displayed so that it can be found and fixed.

Finding and fixing errors is referred to as debugging.

Why ‘Catch’ Exceptions?

When an exception is produced, it is thrown – so to deal with it, we need to catch it.

If an exception is caught, the application will not halt, and you can define your own actions to take with the exception and what the application should do after the exception has been dealt with.

In most cases, errors are caught and then logged somewhere for later inspection when debugging. If it was a minor exception, the application is then allowed to continue as not to interrupt the user. However, some errors will compromise the state of the application too much (meaning that continued operation will result in bad output), and the developer may elect to log the exception and then force the user to restart the application to begin with a clean slate.

In other cases, an exception might be totally expected. Something that crops up that doesn’t actually affect the performance of the application. In these cases, the exception can be caught and ignored.

The Python try/except/finally Statements

In the Python programming language, exceptions are handled using the try/except/finally statements.

These three statements allow you to define which code you want to attempt to run (try), which kinds of errors you want to catch (except), and what to do once the code has been executed or the error has been handled (finally).

The syntax is as follows:

try:
    // Code to execute
except ErrorName:
    // Code to execute in the case of an error
finally:
    // Code to execute when either of the above has completed

Note that:

  • The code contained in the try statement will execute in full or until an exception is encountered
    • The remaining code in the block after an exception or error is encountered will not be executed
  • Multiple except statements can be provided to handle different kinds of exception
    • ErrorName is the name of the exception to catch using the except statement
      • If left blank, all exceptions will be caught
  • The code contained in the finally block will be executed once either the code in the try block has been completed, or if an exception has been thrown and caught, the code in the except block(s) has been completed.
    • If an uncaught exception occurs, the code in the finally block will not be executed.

Examples

Catching All Exceptions

To catch all exceptions, simply use the except statement on its own after a try: statement:

try:
    print( 'hello' / 'there')
except:
    print('Exception thrown')

Above, an exception is thrown (because you can’t perform division on strings) and caught by the except statement, which prints a message.

Getting Exception Details

Details of the exception can be retrieved using the as operator:

try:
    print( 'hello' / 'there')
except Exception as e:
    print(e)

Above, an exception is thrown, and the details are printed. The output is:

TypeError: unsupported operand type(s) for Div: 'str' and 'str' on line 2

This gives us more information on the error – which can be logged, processed, or displayed as required.

Catching Specific Types of Exceptions

In the previous example, you can see that the specific exception thrown is a TypeError. If we wanted to catch only that kind of exception and leave all others uncaught, the class of the exception can be defined when catching to limit which exceptions are caught:

try:
    print( 'hello' / 'there')
except TypeError:
    print('TypeError thrown')

Catching Multiple Types of Exceptions

Multiple except statement can be used to catch multiple types of error. They will be processed in order of appearance – if one is triggered by an exception matching the criteria, the remaining except statements will not be executed:

try:
    print( 'hello' / 'there')
except TypeError:
    print('TypeError thrown')
except NameError:
    print('NameError thrown')
except Exception as e:
        print('An exception occurred that was not NameError or TypeError')

Using else to Execute Code if No Exceptions were Caught

The else statement can be used to execute a code block only if no exception is encountered:

try:
    print('hello' + 'there')
except:
    print('Exception thrown')
else:
    print('No exception thrown')

Doing Nothing If an Exception is Thrown with Pass

Finally, if you are catching an exception and want to do nothing about it, use the pass statement.

Python expects an indented code block to follow an except statement, pass fulfills that while doing absolutely nothing.

try:
    print( 'hello' / 'there')
except:
    pass

 

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment