terbed
11/27/2016 - 11:20 AM

Exceptions.

Exceptions. #python

def print_object(some_object):
    # Check if the object is printable...
    try:
        printable = str(some_object)
    except TypeError:
        print("unprintable object")
    else:
        print(printable)
        
        
def display_username(user_id):
    try:
        db_connection = get_db_connection()
    except DatabaseEatenByGrueError:
        print('Sorry! Database was eaten by a grue.')
    else:
        print(db_connection.get_username(user_id))
        db_connection.cleanup()

        
def calculate_value(self, foo, bar, baz):
    try:
        result = self._do_calculation(foo, bar, baz)
    except:
        self.user_screwups += 1 
        raise
    return result
  
  
""" Here, we have a member function doing some calculation.
We want to keep some statistics on how often the function is misused and throws an exception,
but we have no intention of actually handling the exception. 
Ideally, we want to an exception raised in _do_calculation to be flow back to the user code as normal. 
If we simply raised a new exception from our except clause, the traceback point to our except clause and mask the real issue
(not to mention confusing the user). raise on its own, however, lets the exception propagate normally with its original traceback.
In this way, we record the information we want and the user is able to see what actually caused the exception."""