Skip to content

Python Try Except – easily explained!

Python Try Except is a way to handle so-called exceptions in Python programs so that the application does not crash. With the help of Python Try Except, exceptions can be caught and handled.

What is the difference between Syntax Errors and Exceptions?

As we have probably all had to learn painfully, Python terminates a running program as soon as an error or exception occurs. An important distinction must be made here. The code can stop due to syntax errors, i.e. code that is simply written incorrectly and cannot be interpreted, or due to exceptions, i.e. syntactically correct code components that cause problems during execution.

A syntax error can be caused for example by wrongly set brackets:

Python Try Except

Exceptions, on the other hand, are errors that occur during the execution of the application, even though the code is syntactically correct. This can happen, for example, when trying to add a string and a number together. The code itself is written correctly, but the implementation of this operation is not possible:

Python Try Except

What are the types of exceptions in Python?

In Python, there are many different types of exceptions that can occur when executing code. The following list describes the most common, but not all, types of exceptions:

  • AssertionError: This exception occurs when the command “assert” was not used correctly or generates errors.
  • ImportError: If there are problems importing modules, you get an Import Error. This can happen, for example, if a module, such as Pandas, has not yet been installed, incorrect or non-existent functions are to be loaded from a module, or the module with the specified name simply does not exist.
  • IndexError: When working with Python data objects that have an index, such as Python Tuples or Python Lists, an IndexError can occur if indexes are used that cannot be found in the object.
  • KeyError: Similar to the IndexError, the KeyError occurs when working with Python Dictionaries when a key could not be found in a Dictionary object.
  • MemoryError: When the machine’s memory is no longer sufficient to continue running the Python program, a MemoryError occurs.
  • UnboundLocalError: When working with local variables, an UnboundLocalError can occur as soon as a variable is referenced that has not yet been defined, i.e. that has not yet been assigned a value.

How does Python Try Except work?

The Python Try Except functionality makes it possible to deal with possible exceptions in a targeted manner by defining a routine that precisely describes how to handle the exception. This is especially useful if the probability of an exception is very high or an interruption of the program is to be prevented at all costs.

Two blocks are used for this purpose: Try and Except. The Try block is used to add the code that may cause exceptions during execution. If this code block runs without problems, the following Except block is simply skipped and the code is executed afterward. However, in case there is an exception in the Try block, the code in the Except block is automatically executed.

Python Try Except

In this case, the addition of a and b is always executed, except when values are passed for the two variables that do not number. Then there would actually be a ValueError, but this is caught by our Python Try Except loop. Instead of the ValueError the text “a, b or both were not numbers. Please try again with different values”.

However, in a Python Try Except loop, you don’t necessarily have to specify the specific exception to respond to, it can also be defined to execute the Except block on any exception. In addition, a routine can be defined using “finally” in case the program got by without an exception.

Python Try Except

In which applications does it make sense to use Python Try Except?

In Data Science, it makes sense in many applications to use a Python Try Except loop to avoid terminating the program prematurely:

  • Preparation of large Data Sets: If you want to prepare large datasets for Machine Learning to use as a training dataset, it is not uncommon for the preparation to take several hours. Depending on the quality of the data set, not all data types match the given ones. At the same time, you want to avoid the program stopping halfway through and you don’t notice it. For this, you can use a Python Try Except loop to simply skip individual records whose data quality is not correct and would lead to exceptions.
  • Logging of Software: Here, too, the Python Try Except loop is needed, since the productive application should continue to work. Using the Except block, the error can be output to the logs and can then be evaluated. After the error has been fixed in a newer version, the new state can be deployed and ensures that the downtime of the application is as low as possible.

This is what you should take with you

  • Python Try Except is a way to handle so-called exceptions in Python programs so that the application does not crash.
  • The Try Block encloses the lines that could potentially lead to exceptions. The Except Block, on the other hand, defines the code that should be executed in the event of an error. If no exception occurs, the code after the Python Try Except loop is simply executed.
  • In addition, you can use the “finally” command to define what should happen if no error occurs in the Try Block.

Thanks to Deepnote for sponsoring this article! Deepnote offers me the possibility to embed Python code easily and quickly on this website and also to host the related notebooks in the cloud.

Other Articles on the Topic of Python Try Except

  • At w3schools you can find a detailed article about Python Try Except.
Das Logo zeigt einen weißen Hintergrund den Namen "Data Basecamp" mit blauer Schrift. Im rechten unteren Eck wird eine Bergsilhouette in Blau gezeigt.

Don't miss new articles!

We do not send spam! Read everything in our Privacy Policy.

Cookie Consent with Real Cookie Banner