python - Catching exception from a called function -
i have function reads csv, checks values in rows, , if okay, writes rows new csv file. have few validation functions i'm calling within main function check value , format of rows.
i'm trying implement main function in way when call other validation functions , doesn't check out, skip writing row entirely.
#main function row in reader: try: row['amnt'] = divisible_by_5(row['amnt']) row['issue_d'] = date_to_iso(row['issue_d']) writer.writerow(row) except: continue #validation function def divisible_by_5(value): try: float_value = float(value) if float_value % 5 == 0 , float_value != 0: return float_value else: raise valueerror except valueerror: return none at moment, writer still writing rows should skipped. example, if number not divisible 5, instead of skipping row, writer writing ''.
so, how can handle exception (valueerror) raised in divisible_by_5 in loop don't write lines raise exception?
you can re-raise exception caught in exception handler , have handler call stack handle using an empty raise statement inside except block:
except valueerror: raise # re raises previous exception this way, outer handler in 'main' can catch , continue.
note: is, empty except: block in for loop will catch everything. specifying exception expected (except valueerror in case) considered idea.
more simply, don't put body of validation function divisible_by_5 in try statement. python automatically searches nearest except block defined , uses if current exception matches exceptions specified:
def raiser(): if false: pass else: raise valueerror try: raiser() except valueerror: print "caught" this print caught.
Comments
Post a Comment