Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Pythonic way for "resume next" on exceptions?

The problem: I am reading a series of heterogeneous input files. I wrote a reader class for each of them, which reads the file using __init__(self, file_name), and throws an exception in case of malformed input.

The code looks like this:

clients              = Clients             ('Clients.csv'             )
simulation           = Simulation          ('Simulation.csv'          )
indicators           = Indicators          ('Indicators.csv'          )
legalEntity          = LegalEntity         ('LegalEntity.csv'         )
defaultPortfolio     = DefaultPortfolio    ('DefaultPortfolio.csv'    )
excludedProductTypes = ExcludedProductTypes('ExcludedProductTypes.csv')

The problem is that I want not to die at the first malformed file, but instead read all of them and THEN die if at least one was malformed. The only way to do it that I could find looks horrible:

my errors = []    

try:
    clients              = Clients             ('Clients.csv'             )
except Exception, e:
    errors.append(e)
try:
    simulation           = Simulation          ('Simulation.csv'          )
except Exception, e:
    errors.append(e)
try:
    indicators           = Indicators          ('Indicators.csv'          )
except Exception, e:
    errors.append(e)
try:
    legalEntity          = LegalEntity         ('LegalEntity.csv'         )
except Exception, e:
    errors.append(e)
try:
    defaultPortfolio     = DefaultPortfolio    ('DefaultPortfolio.csv'    )
except Exception, e:
    errors.append(e)
try:
    excludedProductTypes = ExcludedProductTypes('ExcludedProductTypes.csv')
except Exception, e:
    errors.append(e)

if len(errors) > 0:
    raise MultipleErrors(errors)

Is there a better looking way to approach the problem?

like image 705
crusaderky Avatar asked Sep 06 '13 10:09

crusaderky


People also ask

Can we use continue in try catch?

As you are saying that you are using try catch within a for each scope and you wants to continue your loop even any exception will occur. So if you are still using the try catch within the loop scope it will always run that even exception will occur.

What is a try-except statement?

A Try-Except statement is a code block that allows your program to take alternative actions in case an error occurs. CONSTRUCTION: Try-Exception Statement. try: code block 1 except ExceptionName: code block 2. Python will first attempt to execute the code in the try statement (code block 1).

Does Python continue after Except?

If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.

What key words handle exceptions in Python?

Python uses try and except keywords to handle exceptions. Both keywords are followed by indented blocks.


2 Answers

Store the classes and files in a sequence, the results into a dictionary:

inputs = (
    (Clients, 'Clients.csv'),
    (Simulation, 'Simulation.csv'),
    (Indicators, 'Indicators.csv'),
    (LegalEntity, 'LegalEntity.csv'),
    (DefaultPortfolio, 'DefaultPortfolio.csv'),
    (ExcludedProductTypes, 'ExcludedProductTypes.csv'),
)

results = {}
errors = []
for cls, filename in inputs:
    try:
        results[cls.__name__[0].lower() + cls.__name__[1:]] = cls(filename)
    except Exception, e:
        errors.append(e)

if errors:
    raise MultipleErrors(errors)
like image 196
Martijn Pieters Avatar answered Sep 19 '22 05:09

Martijn Pieters


You can try something like this:

handlers_mapping = {
    Clients: 'Clients.csv',
    Simulator: 'Simulator.csv',
    Indicators: 'Indicators.csv',
    LegalEntity: 'LegalEntity.csv',
    DefaultPortfolio: 'DefaultPortfolio.csv',
    ExcludedProductTypes: 'ExcludedProductTypes.csv'
}

results = {}
errors = []
for handler, file_name in handlers_mapping.iteritems():
    try:
        results[handler] = handler(file_name)
    except Exception, e:
        errors.append(e)
like image 29
Yura Avatar answered Sep 21 '22 05:09

Yura