an exception

I changed the name of the configuration file, added one at the end, but the exception is not caught, why?

#!usr/bin/env python #coding:utf-8 import configparser config = confgparser.RawConfigParser() try: config.read('autogen_owen.cfg') except: print ("Отсутсвует конфигурационный файл") else: print (config.get('system', 'version')) 

Closed due to the fact that off-topic participants VenZell , aleksandr barakin , zRrr , user194374, Dmitriy Simushev 27 Mar '16 at 18:05 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - VenZell, aleksandr barakin, zRrr, Community Spirit, Dmitriy Simushev
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • 3
    Please transfer the code and the contents of the exception from the image directly to the question. - VenZell

3 answers 3

You have an Exception in the else block, so NoSectionError is not caught.

If you want to check the existence of the configuration file, it is better to call the os.path.exists method or check the result of the config.read method on an empty list. Since the config.read method ignores the absence of a file and returns an empty list instead of an exception.

    The read method does not throw exceptions. The documentation says "If a file cannot be opened, that file will be ignored." All that remains is to check for the presence of the file using os.path.exists() , or to check the config.has_section('system') .

      Catch any error as follows:

        except NameOfYourError as e: print(e) make_something_with_this() 

      The main thing is to enter this block in the place where you want, and not to be confused with the hierarchy.