“`java
void add(String item, int qty, double rate) {
if (qty <= 0) throw new IllegalArgumentException("Quantity must be positive");
lines.add(new Line(item, qty, rate));
}
try {
List rows = Files.readAllLines(Path.of(“sales.csv”));
Files.writeString(Path.of(“out.txt”), “rows: ” + rows.size());
} catch (IOException e) {
System.err.println(“File problem: ” + e.getMessage());
}
“`
Checked exceptions (like IOException) must be caught or declared; unchecked ones (IllegalArgumentException) signal programming or input errors.
💡 Fail early with a clear message. ‘Quantity must be positive’ beats a wrong invoice total discovered next month.
Code for this course follows standard, current syntax; we test JavaScript and PowerShell scripts before publishing, and R/Java/Rust examples are kept to core language features. Tell us if anything fails on your setup.
Practice
Try adding a line with quantity 0 to see the exception.