Monday, 3 February 2014

Object Oriented Programming continued...

Regarding my question from last week, after re-analyzing the code we looked at in lecture, I realized the problem I had was more with exceptions than classes. When using the format try and except, when an exception is raised in the try clause, the exception clause goes in order as its written. So if certain exceptions are subclasses of other exceptions, they get caught as the superclass exception first and then stop checking the rest of the except clauses. For example, in the code below the special exception would be caught as an Exception and the code that catches it as a SpecialException would never be reached.

class SpecialException (Exception):
     pass

if __name__ == "__main__":
     try: 
          raise SpecialException
     except Exception as e:
          print("caught as Exception")
     except SpecialException as se:
          print("caught as SpecialException")

This is why its very important to keep in mind the order of exceptions and write them in the order of most specific to most general (where specific refers to a subclass and general is a superclass). 

No comments:

Post a Comment