
π This article includes 1 downloadable practice file β
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<String> 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
- πInvoice.javaLesson code file.β¬ JAVA Β· 1 KB
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