Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching exception from a called function

I have a function that reads a CSV, checks the values in the rows, and if everything is okay, it writes the rows to a new CSV file. I have a few validation functions I'm calling within my main function to check the value and format of the rows.

I'm trying to implement my main function in a way so that when I call the other validation functions and something doesn't check out, I skip writing that row entirely.

#main function
for 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 and float_value != 0:
            return float_value
        else:
            raise ValueError
    except ValueError:
        return None

At the moment, the writer is still writing rows that should be skipped. For example, if a number is not divisible by 5, instead of skipping that row, the writer is just writing ''.

So, how can I handle the exception (ValueError) raised in divisible_by_5 in my for loop so I don't write lines that raise an exception?

like image 915
Brosef Avatar asked Jan 05 '16 22:01

Brosef


People also ask

How do you catch an exception from another function?

This way, the outer handler in 'main' can catch it and continue . Note: As is, your empty except: block in the for loop will catch everything. Specifying the exception expected ( except ValueError in this case) is generally considered a good idea. This will print caught .

What happens if an exception is thrown in a function but not caught?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.

What is catch function in exception handling?

The catch block handles the exception. It might rethrow the same exception, throw another exception, jump to a label, return from the function, or end normally. If a catch block ends normally, without a throw , the flow of control passes over all other catch blocks associated with the try block.

How do you throw an exception from one method to another in C#?

C# - throw keywordAn exception can be raised manually by using the throw keyword. Any type of exceptions which is derived from Exception class can be raised using the throw keyword. Output: Student object is null.


1 Answers

You can re-raise an exception caught in an exception handler and have another handler up the call stack handle it by using an empty raise statement inside the except block:

except ValueError:
    raise  # re raises the previous exception

This way, the outer handler in 'main' can catch it and continue.

Note: As is, your empty except: block in the for loop will catch everything. Specifying the exception expected (except ValueError in this case) is generally considered a good idea.


More simply, don't put the body of your validation function divisible_by_5 in a try statement. Python automatically searches for the nearest except block defined and uses it if the current exception matches the exceptions specified:

def raiser():
    if False: 
        pass
    else:
        raise ValueError

try:
    raiser()
except ValueError:
    print "caught"

This will print caught.

like image 176
Dimitris Fasarakis Hilliard Avatar answered Sep 28 '22 09:09

Dimitris Fasarakis Hilliard