Exception Handling & File Processing¶
Ⅶ Exception Handling¶
01. What is Exception Handling?¶
Programs can encounter unexpected situations at runtime.
int("hello") # ValueError
10 / 0 # ZeroDivisionError
[1,2,3][10] # IndexError
When this happens, Python raises an Exception. If unhandled, the program stops.
Exception handling prepares for these error conditions so the program can keep running.
try / except Basic Structure¶
try:
x = int(input("Number: "))
print(10 / x)
except ValueError:
print("Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else / finally¶
try:
x = int(input("Number: "))
result = 10 / x
except (ValueError, ZeroDivisionError) as e:
print(f"Error: {e}")
else:
print(f"Result: {result}") # only runs if no exception
finally:
print("Always runs") # runs regardless of exception
| Clause | When it runs |
|---|---|
try |
Always attempted |
except |
When an exception occurs |
else |
When no exception occurs |
finally |
Always (exception or not) |
02. Common Exception Types¶
| Exception | Cause | Example |
|---|---|---|
ValueError |
Wrong type conversion | int("hello") |
ZeroDivisionError |
Division by zero | 10 / 0 |
IndexError |
Index out of range | [1,2][5] |
KeyError |
Missing dictionary key | {"a":1}["b"] |
TypeError |
Type mismatch | "1" + 1 |
FileNotFoundError |
File doesn't exist | open("x.txt") |
AttributeError |
Missing attribute/method | "hi".append(1) |
raise — Raising Exceptions Manually¶
def set_age(age):
if age < 0:
raise ValueError("Age must be 0 or greater.")
return age
Ⅷ File Processing¶
01. What is File Processing?¶
File processing means opening, reading, writing, and closing files in a program.
File Modes¶
| Mode | Meaning |
|---|---|
"r" |
Read (default; error if file missing) |
"w" |
Write (creates new; overwrites existing) |
"a" |
Append (keeps existing; adds to end) |
"x" |
Create (error if file already exists) |
with Statement (Recommended)¶
with open("hello.txt", "w") as f:
f.write("Hello, World!")
# file is automatically closed when the with block ends
02. Writing to Files¶
# write() — write a string
with open("memo.txt", "w", encoding="utf-8") as f:
f.write("Line 1\n")
f.write("Line 2\n")
# writelines() — write a list of strings
lines = ["apple\n", "banana\n", "strawberry\n"]
with open("fruits.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
# append mode — add without erasing
with open("memo.txt", "a", encoding="utf-8") as f:
f.write("Line 3\n")
03. Reading Files¶
# read() — read entire file
with open("memo.txt", "r", encoding="utf-8") as f:
content = f.read()
# readline() — read one line at a time
with open("memo.txt", "r", encoding="utf-8") as f:
line = f.readline() # "Line 1\n"
# readlines() — read all lines as a list
with open("memo.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
# for loop — best for large files
with open("memo.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
Combining File I/O with Exception Handling¶
try:
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
except FileNotFoundError:
print("File not found.")
Key Summary¶
| Concept | Description |
|---|---|
try / except |
Handle exceptions — prevent program crash |
else |
Runs only when no exception |
finally |
Always runs regardless of exception |
raise |
Manually trigger an exception |
open(path, mode) |
Open a file |
"w" / "a" / "r" |
Write / Append / Read mode |
with statement |
Auto-close — safe even on exception |
encoding="utf-8" |
Required for non-ASCII (e.g., Korean) files |