8 Error Handling
What happens when there is an error:
Fail Silently
Make sure to document the behaviour in the method docstring.
Example:
if not self.is_empty():
return self._items.pop()
Raise a user-defined exception
class EmptyStackError(Exception):
"""Exception will be raised when calling pop on an empty stack."""
pass
def pop(self)-> any:
""" Remove and return the element at the top of this stack.
Raise an EmptyStackError if this stack is empty.
>>> s = Stack()
>>> s. push('hello')
>>> >. > s. push( 'goodbye')
>>> s. pop ()
'goodbye'
"""
if self. is_empty():
raise EmptyStackError
else:
return self._items.pop()
To customize the message:
class EmptyStackError(Exception):
"""Exception raised when calling pop on an empty stack."""
def __str__(self)->str:
return 'You called pop on an empty string'
Error Handling Example
if __name__ == '__main__':
option = 'y'
while option == 'y':
value = input( 'Give me an integer to check if it is a divisor of 42: ')
try:
is_divisor = (42 % int(value) == 0)
print(is_divisor)
except ZeroDivisionError:
print("Uh-oh, invalid input: O cannot be a divisor of any number!")
except ValueError:
print("Type mismatch, expecting an integer!")
finally:
print("Now let's try another number...")
option = input( 'Would you like to continue (y/n): ')
When having error handling in a function the type contract must change
def second_from_top(s: Stack) -> Optional[str]:
"""Return a reference to the item that is second from the top of s.
Do not change s.
If there is no such item in the Stack, returns None.
"""
hold2 = None
try:
# Pop and remember the top 2 items in s.
hold1 = s. pop ()
hold2 = s. pop ()
# Push them back so that s is exactly as it was.
s. push(hold2)
s. push(hold1)
# Return a reference to the item that was second from the top.
except EmptyStackError:
print( "Cannot return second from top, stack empty")
return hold2
Exceptions and Memory
When an exception is raised, the function ends, and its stack frame is popped (like a return statement); however, the exception is returned to the caller, who in turn ends immediately and sends the exception back to its caller until the entire stack frame is popped.