Errors and Exception Handling¶

Ha Khanh Nguyen (hknguyen)

1. try/except¶

• Many functions only work on certain kinds of input.
• For example, the int() function fails with string that contains anything other than number!
• Suppose we want a version of int() that instead of throwing an error, it just simply returns the input string!
• This can be done by writing a function that enclosed the call to int() in a try/except block:
• The code follows except will only be executed if int() raises an exception.
• You might notice that int() can raise exceptions other than ValueError:
• You might want to only suppress ValueError, since a TypeError (the input was not a string or numeric value) might indicate a bigger bug. To do that, write the exception type after except:
• You can catch multiple exception types by writing a tuple of exception types instead (the parentheses are required):

2. finally¶

• There are cases where even though there is an exception, you still want some code to be executed regardless.
• To do this, use finally keyword:
• Similarly, you can have code that executes only if the try: block succeeds using else:

3. Exercise¶

Let s be a string that contains a simple mathematical expression, e.g.,

s = '1.5 + 2.1'

s = '10.0-1.6'

s = '3.1*5.8'

s = '4.7 /7.2'

The expression will only have 2 operands and the operator will be one of the following: +, -, * and /.

Write a function that interprets the expression, then evaluates it and returns the result. If the input string s does not follow the format above, simply return a None object.

This lecture note is modified from Chapter 3 of Wes McKinney's Python for Data Analysis 2nd Ed.