Menu Close

Python Try and Except Statements

Often in Python, there will be code that will throw exceptions. This is often not avoidable, so programmers use try and except statements to make sure that code will still function. This can also be used to test for errors, or for debugging purposes.

These code blocks will always have the keywords try and except, however the keywords else and finally can also be used for other circumstances.

Try Statement:

The try statement is used to determine which block of code to test. Below is the syntax for the try statement.


Except Statement:

The except statement will only run if the try statement produces an error. Otherwise, it will be ignored. The syntax is below.


There can also be different except statements for different types of errors.
Here are a few examples of such:

except RuntimeError:

except ValueError:

There can also be an except statement that can pass any exception, creating a more universal expression.

except Exception as e:

Else Statement :

The else statement runs if the try statement does not produce any errors. It follows the except statement.


Finally Statement:

The finally statement will run regardless of whether the try statement produces an error or not.


Raise keyword:

The raise keyword is used to raise exceptions for debugging reasons. It helps other programmers understand why the code failed to execute. It defines the error, as well as a message to show to the user. Below is the syntax for the raise keyword.

except error:
    raise error(“message”)

Example 1:

The code block below adds the first 5 values in a list.

#precondition: there is a list created called myList
total = 0

    for i in range(5):
        total += myList

except TypeError:
    raise TypeError(“item in list not type int”)

except IndexError:
    raise IndexError(“List shorter than 5”)

myList Test Values:

[1, 2, 3, 4, 5]
[“1”, “2”, “3”, “4”, “5”]
[1, 2, 3, 4]


TypeError: item in list not type int
IndexError: List shorter than 5

With the example above, it shows the usage of multiple exceptions for one try statement.

Example 2:

The code below tests for certain names within a list of people.

#precondition: there is an input value known as testName
nameList = [“John”, “Francis”, “Mary”, “Jason”, “Richard”]


except ValueError:
    print(“Person not in list”)

    print(“Person is in list”)

    print(“Test complete”)

testName Test Values:



Person is in list
Test complete

Person is in list
Test complete

Person not in list
Test complete

In the code above, we can see that the except and else statements are not executed together, as it is always one or the other. However, the finally statement is always executed.

Posted in Embedded Programming Language, Python

Related Articles

Leave a Reply

Your email address will not be published.

Leave the field below empty!