try:
n = int(user_input)
except ValueError:
n = 0
print("Couldn't parse the number, defaulting to 0.")
Python runs the try block. If a ValueError is raised, control jumps to the except block. If no error, the except is skipped.
ValueError — the value was the right type but wrong content (e.g. int("abc")).TypeError — the value was the wrong type.KeyError — that key didn't exist in the dict.FileNotFoundError — couldn't find that file.# OK but lazy — swallows bugs you'd want to know about
try:
do_thing()
except:
pass
# Better — explicit about what you expect
try:
do_thing()
except FileNotFoundError:
print("File missing, skipping.")
f = open("data.txt")
try:
work_with(f)
except Exception as e:
print(f"Failed: {e}")
finally:
f.close() # runs whether we succeeded or not
Loop through all CSVs in a folder. Try to read each. If one is broken, log it and keep going — don't let one bad file stop the rest.
import pandas as pd
from pathlib import Path
results = []
for path in Path("monthly_files").glob("*.csv"):
try:
df = pd.read_csv(path)
results.append((path.name, len(df)))
except Exception as e:
print(f"Skipped {path.name}: {e}")
print(f"Processed {len(results)} files successfully")
try.ValueError, FileNotFoundError etc.finally for cleanup that must always run.Write a function to_float(text) that returns a float if it can, or None if it can't. Then test it with: "12.5", "abc", "", "100".