6 Exception Handling

The try statement works as follows:
- First, the try clause (the statement(s) between the try and except keywords) is executed
- If no exception occurs, the except clause is skipped and execution of the try statement is finished
- If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement
- If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above

A try statement may have more than one except clause, to specify handlers for different exceptions.

6.1 Catching Error

Different exception object has different attributes.

  a = 1 + 'a'
## known error  
except TypeError as err:
  print('I know this error !!!!',
        '\n Error: ', err,
        '\n Args:  ', err.args,
        '\n Type:  ', type(err))

## all other error
except Exception as err:
  print( 'Error: ', err,
         '\nArgs:  ', err.args,
         '\nType:  ', type(err))
#:> I know this error !!!! 
#:>  Error:  unsupported operand type(s) for +: 'int' and 'str' 
#:>  Args:   ("unsupported operand type(s) for +: 'int' and 'str'",) 
#:>  Type:   <class 'TypeError'>

6.2 Custom Exception

  raise Exception('bloody', 'hell')  #simulate exception
except Exception as err:
  print( 'Error: ', err,
         '\nArgs:  ', err.args,
         '\nType:  ', type(err))
#:> Error:  ('bloody', 'hell') 
#:> Args:   ('bloody', 'hell') 
#:> Type:   <class 'Exception'>