FileNotFoundError thrown due to file name in file, rather than file itself

dieter.maurer at online.de dieter.maurer at online.de
Mon Nov 11 12:24:44 EST 2024


Loris Bennett wrote at 2024-11-11 15:05 +0100:
>I have the following in my program:
>    try:
>        logging.config.fileConfig(args.config_file)
>        config = configparser.ConfigParser()
>        config.read(args.config_file)
>        if args.verbose:
>            print(f"Configuration file: {args.config_file}")
>    except FileNotFoundError:
>        print(f"Error: configuration file {args.config_file} not found.  Exiting.")

Do not replace full error information (including a traceback)
with your own reduced error message.
If you omit your "try ... except FileNotFoundError`
(or start the `except` clause with a `raise`), you
will learn where in the code the exception has been raised
and likely as well what was not found (Python is quite good
with such error details).

> ...
>My questions are:
>
>1. Should I be surprised by this behaviour?

Your code contains a major weakness (see above); thus surprises
are not unlikely.

>2. In terms of generating a helpful error message, how should one
>   distinguish between the config file not existing and the log file not
>   existing?

You look at the error information provided by Python
(and its library) rather than hiding it.


More information about the Python-list mailing list