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.

try:
    #code

Except Statement:

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

except:
    #code

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

except RuntimeError:
    #code

except ValueError:
    #code

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

except Exception as e:
    print(e)

Else Statement :

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

else:
    #code

Finally Statement:

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

finally:
#code

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

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

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]

Outputs:

15
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”]

try:
    nameList.remove(testName)

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

else:
    nameList.append(testName)
    print(“Person is in list”)

finally:
    print(“Test complete”)

testName Test Values:

Jason
Francis
Bobby

Outputs:

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!