Programming from zero

Handle a missing config file without crashing

mediumErrors and exceptions Must-do

Problem statement

A script reads its port from config.txt, a file containing a single line such as 9090. If the file does not exist, print config.txt not found, using defaults and fall back to port 8080. Either way, finish by printing Port: N.

Examples

Example 1

Input: config.txt does not exist.

Output: config.txt not found, using defaults Port: 8080

Hints

Approach

Optimal

Set port = 8080 first, so there is always a sensible value. Then try to open and read the file inside a try: block; if it exists, f.read().strip() gets the text and int() converts it, replacing the default. If the file is missing, open() raises FileNotFoundError, and the except block prints a warning while the default stays in place. The final print sits outside the try, so it runs in both cases. This "default, then try to override" pattern is how most tools treat optional config files.

Python
port = 8080
try:
with open("config.txt", encoding="utf-8") as f:
port = int(f.read().strip())
except FileNotFoundError:
print("config.txt not found, using defaults")
print(f"Port: {port}")

Follow-up questions

  • Also catch ValueError and print config.txt is not a valid number, using defaults.

Frequently asked questions

Then int() raises ValueError, which this code does not catch, so the script stops. You can handle both with except (FileNotFoundError, ValueError):, but it is often better to give each its own message, since a broken config is a different problem from a missing one.

That works, but the file could disappear between the check and the open. Trying the operation and handling the error is the common Python style and avoids that gap.