Handle a missing config file without crashing
Problem statement
A missing file is one of the most common failures in real scripts. A config file may not be deployed yet, or the path may be wrong.
Instead of crashing, a good script:
- Tries to open the file.
- Catches the "file not found" error.
- Prints a clear message and falls back to a default value.
The three languages report this differently:
- Python raises
FileNotFoundError. - Java throws
FileNotFoundException. - C++ raises nothing. A stream that failed to open is simply "not open", so you check it yourself.
Common mistake: catching every possible error with no detail.
Wrong:try: f = open(path)except: print("something went wrong")A bare except: also hides typos and other real bugs, and it never says what failed. Catch FileNotFoundError and say which file is missing.
Your task: app.conf exists and holds port=9090 (the code below creates it). missing.conf does not exist. Write read_config(path) that returns the first line of the file. If the file is missing, it prints <path> not found, using default and returns port=8080. Call it for both files and print what each call returns.
Expected output
port=9090missing.conf not found, using defaultport=8080Approach
Try to open and read the file. If it is missing, print the message and return the default:
- Python:
except FileNotFoundError:handles only the missing-file case. - Java:
catch (FileNotFoundException e)handles it. The method still declaresthrows IOExceptionbecause reading can fail in other ways. - C++: there is no exception, so
if (!file.is_open())checks whether opening worked.
The setup line only creates app.conf.
# Setup: create a config file (missing.conf is deliberately not created)
with open("app.conf", "w") as f:
f.write("port=9090\n")
def read_config(path):
try:
with open(path) as f:
return f.readline().strip()
except FileNotFoundError:
print(f"{path} not found, using default")
return "port=8080"
print(read_config("app.conf"))
print(read_config("missing.conf"))