../_images/book_cover.jpg

This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists, the content is also available at Berkeley Python Numerical Methods.

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon!

< 10.2 Avoiding Errors | Contents | 10.4 Type Checking >

Try/Except

Often it is important to write programs that can handle certain types of errors or exceptions gracefully. More specifically, the error or exception must not cause a critical error that makes your program shut down. A Try-Except statement is a code block that allows your program to take alternative actions in case an error occurs.

CONSTRUCTION: Try-Exception Statement


try:
    code block 1
except ExceptionName:
    code block 2

Python will first attempt to execute the code in the try statement (code block 1). If no exception occurs, the except statement is skipped and the execution of the try statement is finished. If any exception occurs, the rest of the clause is skipped. Then if the exception type matches the exception named after the except keyword (ExceptionName), the code in the except statement will be executed (code block 2). If nothing in this block stops the program, it will continue to execute the rest of the code outside of the try-except code blocks. If the exception does not match the ExceptionName, it is passed on to outer try statements. If no other handler is found, then the execution stops with an error message.

EXAMPLE: Capture the exception.

x = '6'
try:
    if x > 3:
        print('X is larger than 3')
except TypeError:
    print("Oops! x was not a valid number. Try again...")
Oops! x was not a valid number. Try again...

EXAMPLE: If your handler is trying to capture another exception type that the except does not capture it, then we will end up with an error and the execution stops.

x = '6'
try:
    if x > 3:
        print('X is larger than 3')
except ValueError:
    print("Oops! x was not a valid number. Try again...")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-899d928e7a1f> in <module>
      1 x = '6'
      2 try:
----> 3     if x > 3:
      4         print('X is larger than 3')
      5 except ValueError:

TypeError: '>' not supported between instances of 'str' and 'int'

Of course, a try statement may have more than one except statement to handle different exceptions or you can not specify the exception type so that the except will catch any exception.

x = 's'

try:
    if x > 3:
        print(x)
except:
    print(f'Something is wrong with x = {x}')
Something is wrong with x = s

EXAMPLE: Handling multiple exceptions.

def test_exceptions(x):
    try:
        x = int(x)
        if x > 3:
            print(x)
    except TypeError:
        print("Oops! x was not a valid number. Try again...")
    except ValueError:
        print("Oops! Can not convert x to integer. Try again...")
    except:
        print("Unexpected error")
x = [1, 2]
test_exceptions(x)
Oops! x was not a valid number. Try again...
x = 's'
test_exceptions(x)
Oops! Can not convert x to integer. Try again...

Another useful thing in Python is that we can raise some exception in certain cases using raise. For example, if we need x to be less than or equal to 5, we could use the following code to raise an exception if x is larger than 5. The program will display our exception and stops the execution.

x = 10

if x > 5:
    raise(Exception('x should be less or equal to 5'))
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-7-99b32b52c4f8> in <module>
      2 
      3 if x > 5:
----> 4     raise(Exception('x should be less or equal to 5'))

Exception: x should be less or equal to 5

WARNING! Try-except statements should never be used in place of good programming practice. For example, you should not code sloppily and then encase your program in a try-except statement until you have taken every measure you can think of to ensure that your function is working properly.

< 10.2 Avoiding Errors | Contents | 10.4 Type Checking >