Tuesday, April 19, 2011

How to work with exceptions

Here is:
  • How to define an exception
  • How to raise an exception
  • How to catch an exception

class MyException(Exception): # a custom exception
 """ My own exception class """
 def __init__(self,value):
  self.value = value
 def __str__(self):
  return repr(self.value)

def myFunction(): # this function will raise a exception
 print "The shuttle is landed"
 raise MyException("Huston, we have a problem")

def handleException(): # this function will handle the exception
 except MyException, e:
  print "Something is going wrong:", e.value

## test the exception handling ##
The shuttle is landed
Something is going wrong: Huston, we have a problem

No comments:

Post a Comment