# 01 - catch a general error def do_something(thing): x = 0 try: x = 1 print 'Hello' + thing x = 2 print x except: print x def main(): do_something(4) if __name__ == '__main__': main() # All the legal commands inside the 'try' block are # executed normally. If any exception is raised, the # processor jumps to the except section for that 'try' #---------------------------------------------------------------- # 02 - catch a specific error (s) in the order written def do_something(thing): x = 0 y = 1 try: y = 2 y = y / x # If we comment this, falls into the next (general exception) print 'Hello' + thing print x except ZeroDivisionError: print x, ' is zero' except: print 'Error in print' def main(): do_something(4) if __name__ == '__main__': main() #----------------------------------------------------------------- # 03 - finally - do it whether or not exception had occurred # if the exception did not capture the error, it will still # execute the 'finally' clause, and then show the error def do_something(thing): x = 0 y = 1 try: y = 2 print 'Hello' + thing print x except ZeroDivisionError: # Only catches zero division error print x, ' is zero' finally: print 'The final frontier' def main(): do_something(4) if __name__ == '__main__': main() #---------------------------------------------------------------- # Does catch the error def do_something(thing): x = 0 y = 1 try: y = 2 print 'Hello' + thing print x except: print 'general error' finally: print 'The final frontier' def main(): do_something(4) if __name__ == '__main__': main() #-------------------------------------------------------------------------- # 04 - intentionally raising an error (builtin) def do_something(thing): x = 0 y = 1 try: # Using builtin exception raise MemoryError('Total recall , you have lost your memory') except MemoryError as e: print e finally: print 'The final frontier' def main(): do_something(4) if __name__ == '__main__': main() #--------------------------------------------------------------------------- # 05 Define your own exception, if builtins are insufficient # We need to create a class that inherits from Exception class Myexception(Exception): def __init__(self, msg): self.msg = msg def print_exception(self): print 'User defined exception:', self.msg def main(): counter = 5 try: if counter < 10: raise Myexception('counter must be not less than 10') except Myexception as e: # Create object e from class e.print_exception() # Use method on object e else: print 'no error occurred' # if we change the 5 to 5, this prints if __name__ == '__main__': main()