Skip to content

Throw exception instead of sys.exit in GA.__init__ #213

Closed
@holasjuraj

Description

@holasjuraj

Use-case:

Minimal example:

def run_ga(**kwargs):
    try:
        ga = pygad.GA(**kwargs)
        ga.run()
        return ga
    except Exception as e:
        my_custom_logger.print(f"GA failed with kwargs = {kwargs} with exception {e}")
        return None

my_ga = run_ga(num_generations=-1)

Desired behavior:

Program runs, and logs an exception with details about the error - i.e. that num_generations has to be positive.

Current implementation:

With the current sys.exit(-1) in GA.__init__, this will not be caught by the except block. Even if we change the except Exception to except SystemExit (which nobody should ever do), then it would log only the SystemExit with no details into my_custom_logger.

Proposed change:

In the GA.__init__, we can replace the end of the function. Instead of the current:

 except Exception as e:
    self.logger.exception(e)
    sys.exit(-1)

We can rather use:

 except Exception as e:
    self.logger.exception(e)
    raise e

This way, the exception will be logged properly into self.logger, but then it will not kill the whole python process, but rather re-raise the exception. The caller of pygad.GA() can then decide whether this exception will be left uncaught and will exit the program, or they will catch it and act upon it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions