AnsweredAssumed Answered

How to raise exception from if statement in Python

Question asked by geoffreywestgis on Apr 3, 2015
Latest reply on Apr 6, 2015 by curtvprice

This is a general python question, I would like to write a function that essentially states if data is available do this, if not raise an error, and a finally block which does something else.

 

In another function I would like write another if statement that says if function 1 raised an error do this, if not then do this.

 

My question is, how do I reference this raised user-defined exception from my first function?  Here is a code-block that I am working with. 

 

For example, if there is a raised error for NoData, I would like to say in another function, if NoData is raised then do this....

 

 

This block returns:

Traceback (most recent call last):

  File "C:/Users/Administrator/Desktop/DevSummitJSON_PySeminar.py", line 231, in <module>

    servicequery(CreatedDate, now_minus_10)

  File "C:/Users/Administrator/Desktop/DevSummitJSON_PySeminar.py", line 227, in servicequery

    raise DataError, "Exception: Data is older than 10 minutes"

__main__.DataError: Exception: Data is older than 10 minutes

 

# severely edited, since improper indentation etc, precludes providing a test environment
import arcpy    # not in original
arr = #####     # not in original
fc = ####        # not in original
sr = ####       # not in original
NumPyArray = arcpy.da.NumPyArrayToFeatureClass(arr, fc, ['longitudeshape', 'latitudeshape'], sr)  
i = 5  
i2= 10  
now_minus_5 = Start - datetime.timedelta(minutes =i)  
now_minus_10 = Start - datetime.timedelta(minutes =i2)  
class DataError(Exception):
  pass  
class NoDatainLast5(Exception):  
  message = '\nException: NumberTooBigError:\nYour number is too big. \nTry a smaller one!'  
class NoDatainLast10(Exception):  
  message = '\nException: NumberTooBigError:\nYour number is too big. \nTry a smaller one!'  
def checkData(CreatedDate):  
  if CreatedDate > now_minus_10:  
    raise NoDatainLast10  
  elif CreatedDate > now_minus_10:  
    raise NoDatainLast5  
  elif CreatedDate is NULL :  
    raise DataError  
def servicequery(CreatedDate, now_minus_10):  
  if CreatedDate > now_minus_10:  
    NumPyArray  #see at the top
  elif CreatedDate < now_minus_10:  
    raise DataError, "Exception: Data is older than 10 minutes"  
  else:  
    print "test"  
servicequery(CreatedDate, now_minus_10) 

 

Message was edited by: Dan Patterson I had to reformat the whole script due either to an incorrect format selection or source code was wrong.  Added lines at the top of the code to facilitate testing using the edited script.

Outcomes