Java Lesson 7: Exceptions and Files

📎 This article includes 1 downloadable practice file ↓

⏱ 1 min read

📘 Java Beginner Course · Lesson 7 of 8

“`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.

📎 Practice files for this article

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong