cosmogonies.net Blog of cosmogonies.net

search
mail
6May/120

APyTA_12: Handling exceptions, just in case

APyTA_12: Handling exceptions, just in case

Let's see now, how python will help you to manage errors and failure! Yes it can do that too!
try #Test if the next instruction is valid
except #Coupled with try, create a scope in case of try failure
finally #Coupled with try, open a scope independent of try success
raise
#Throw a custom-exception, defined as a class

No full explanation needed here, just see the magic by yourself:

aList=[]
try:
  Doomed = aList[56]  # Error: IndexError: list index out of range #
except :
  print("ERROR")
else:
  print("OK")
finally:
  print("Anyway...")

try:
  Doomed = aList[56]
except IndexError:
  print("ERROR On Index")

try:
  print("toto="+45)
except TypeError: # Error: TypeError: cannot concatenate 'str' and 'int' objects #
  print("ERROR On Type")

Because you sometimes (often?) can't manage all the cases combination that will define your context when computing,
these tools helps you to handle an unexpected and behave accordingly.
You can just let the except keyword alone, or differentiate your scopes to execute, depending on your error type
(You can find all errors types at the address : http://docs.python.org/tutorial/errors.html)

By the way , with raise keyword, you will be able to create your own type of errors, using classes.
(cf further about classes and object creation).

import pymel.core.general
class UnitarySelectionError(BaseException):
  pass

def validSelection():
  currentSelection = pymel.core.general.ls(selection=True, transforms=True)
  if(len(currentSelection)>1):
    raise UnitarySelectionError()
  else:
    print currentSelection[0].name()

try:
  validSelection()
except UnitarySelectionError:
  print("The user have selected more than one transform")
except:
  print("The user have selected nothing!!") #Reached because we do not handle an empty selection, so it is an IndexError at line17
else:
  print("It's ok, you can go on") #Reached if your selection is one transform object)
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.

site-map