A
A
Andrey Begin2022-02-18 11:14:31
PyCharm
Andrey Begin, 2022-02-18 11:14:31

Is the exception thrown even when it is handled?

I handle an exception

try:
    if not self._load_train_data:
        raise Exception('Some exception')
except Exception as ex:
    self.x = self._tensor_x()


The code ends with the following error:

Traceback (most recent call last):
  File "/tmp/pycharm_project_751/predictors/houses_predictor.py", line 299, in _cook_x
    raise Exception('Some exception')
Exception: Some exception


It is necessary to make it so that the exception simply executes the expression in Exception, i.e.

self.x = self._tensor_x()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shurshur, 2022-02-18
@shurshur

That another exception may occur while handling an exception is just normal. It's not normal that all this is masked by catching the root Exception class.
It's bad practice to catch any Exception and not even print its contents with at least regular print. For example, in the bowels of the called code, an error occurs due to the exhaustion of disk space, in the handler you call this code again and the same thing happens in the bowels. Anything can happen there. Run out of memory in absolutely any line, for example.
It's also bad practice to throw an abstract Exception on a specific error. This may be suitable for a script sketched for a one-time run, but in general it is bad, especially since it is not difficult to solve:

class NoTrainDataLoaded(Exception):
    pass

...
raise NoTrainDataLoaded("Call your_model_object.load_train_data first!")

...
try:
    ...
except NoTrainDataLoaded:
    logger.info("Train data not loaded yet, load default data...")
    my_model.load_train_data("mimimi-cats-and-dogs")
    continue

If suddenly an exception occurs that is not mentioned in except, then the script will fall, and this is good. Let him not try to make any kind of reaction to an unclear mistake.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question