05-Exceptions and Assertions
ipynb11 kBPython · 23 cellsSlides of chapter 0
Exceptions and Assertions
Jupyter notebooks
This is a space where text and code come together to form a coherent document. Throughout the course, we will make use of Jupyter notebooks for illustration purposes and for experimentation.
Motivation
Encountering errors is a natural part of programming (happens more often for beginners). Reading and understanding source of errors is crucial for successful implementation of an idea: - Reading error messages help us grasp coding rules - Understanding error messages helps avoid bad or unexpected behavior in code
Exceptions
Python exceptions occur whenever the interpreter cannot execute a line of code. We have seen many kind of exceptions so far, such as TypeError, NameError, and ValueError exceptions. It is normal to encounter errors while programming, but a programmer should write code that handles exceptions well in case they occur. Handling exceptions makes sure that the program does not crash in unfamiliar cases.
The try-except structure
The try-except structure allows handling specific or general exceptions when they occur. Let's examine an example that might result in an exception:
x = int(input("Enter an integer: "))
y = int(input("Enter an integer: "))
z = x/y
print(z)Enter an integer: 10 Enter an integer: 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[1], line 4
1 x = int(input("Enter an integer: "))
2 y = int(input("Enter an integer: "))
3
----> 4 z = x/y
5 print(z)
ZeroDivisionError: division by zeroHere, we might get either:
ZeroDivisionError: if y == 0.ValueError: if user enters non-integer values.
The try-except structure allows to handle previous errors by:
- Placing our code inside a
tryblock - Writing
exceptblocks for each expected error
try:
x = int(input("Enter an integer: "))
y = int(input("Enter an integer: "))
z = x/y
print(z)
except ZeroDivisionError:
print("Cannot divide by 0!")
except ValueError:
print("Bad input! Please enter integers.")Enter an integer: 10 Enter an integer: 0 Cannot divide by 0!
In addition, we can avoid writing except blocks for each error if we want to handle all errors at once. We do so by writing:
try:
x = int(input("Enter an integer: "))
y = int(input("Enter an integer: "))
z = x/y
print(z)
except:
print("Bad Input!")Enter an integer: 10 Enter an integer: abc Bad Input!
Here, the except block handles all types of exceptions but prints the same message. Hence there is a tradeoff between lines of code written and detail of the display message.
Optional clauses in try-except
We can end a try-except block with an optional else clause, the statemens under which get executed only if no exceptions occurs. This optional else clause is placed after all except clauses. Example:
try:
x = int(input("Enter an integer: "))
y = int(input("Enter an integer: "))
z = x/y
except:
print("Bad Input!")
else:
print(z)Enter an integer: 10 Enter an integer: 4 2.5
We can end a try-except block with an optional finally clause, the statemens under which always get executed, whether an exception is raised or not. This optional finally clause is placed after all except clauses. Example:
try:
a = input("Enter an integer: ")
x = int(a)
b = input("Enter an integer: ")
y = int(b)
z = x/y
except:
print("Bad Input!")
else:
print(z)
finally:
print("Original inputs:", a, b)Enter an integer: 10 Enter an integer: 2 5.0 Original inputs: 10 2
Assertions
In Python, we can raise an AssertionError to prevent code from further
execution. For example, recall our user-defined my_sqrt() function: we need the code to stop if the function is given an invalid input for example.
The syntax for raising an assertion is the following:
assert boolean_condition, 'Error message.'--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[6], line 1 ----> 1 assert boolean_condition, 'Error message.' NameError: name 'boolean_condition' is not defined
The assert statement will try to assert that boolean_condition is True. If not, it will display the message: 'Error message'.
Let's try to implement an assertion in our user-defined square-root function:
def my_sqrt(x, epsilon=1E-5):
assert (type(x) == int or type(x) == float) and x >=0, "Bad input!"
# begin function definition
...In the above (truncated) function definition, an assert statement is placed before the code enters the rest of the function to verify that the input x is appropriate. The code will raise an AssertionError: Bad input! if the boolean condition before it is False.
We can refine our assertions even further to check or more conditions, for example, if epsilon is also appropriate:
def my_sqrt(x, epsilon=1E-5):
condition_1 = (type(x) == int or type(x) == float) and x >=0
assert condition_1, "Bad input x!"
condition_2 = type(epsilon) == float
assert condition_2, "Error tolerance must be a float!"
condition_3 = 0 < epsilon and epsilon <= 0.1
assert condition_3, "Error tolerance is not in interval ]0, 0.1]"
# begin function definition
...
In the above (truncated) function definition, three assert statements are placed before the code enters the rest of the function to verify that the inputs conform to what we need them to.