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
 try:
  myFunction()
 except MyException, e:
  print "Something is going wrong:", e.value

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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.