Exceptions & file I/O — cheat sheet
From: fundamentals/08-exceptions.md, fundamentals/09-files.md.
Exceptions
- An exception is what the runtime throws when something goes wrong that the type system alone couldn't prevent (index out of bounds, null dereference, missing file, ...). Unhandled, it crashes the program.
try { ... } catch (SomeException e) { ... }— attempt code that might throw, and define what to do if it does.- A variable declared inside a
tryblock is out of scope outside it. - Catch the specific exception type, not the generic
Exception— e.g.IndexOutOfBoundsException,UnsupportedOperationException,NullPointerException. Check a method's JavaDoc if unsure what it can throw. - Keep
tryblocks small — every statement inside is a potential jump point to acatch, so a largetryblock is harder to reason about than several small, targeted ones. - Prefer preventing the error over catching it when a straightforward check exists (e.g.
if (list.isEmpty())beforelist.get(0), instead of catchingIndexOutOfBoundsException). - Propagation ("throw early, catch late"): instead of handling an exception right where it can occur, declare
throws SomeExceptionon the method and let the caller decide whether to handle it or propagate it further ("dropping it down the call stack"). Deciding the right place to actually catch it is application-specific, not a fixed rule. - Checked exceptions (like
IOException) force you to either catch or declarethrows— the compiler won't let you ignore them, unlike unchecked/runtime exceptions.
File I/O (java.nio.file)
Path.of("relative/path.txt")— points at a file location, relative to the project root by default (in IntelliJ, typically startingsrc/...).- Reading:
Files.readAllLines(path)→List<String>. ThrowsIOException. - Writing:
Files.write(path, lines)— creates the file if missing, replaces its content if it exists. ThrowsIOException.Files.write(path, lines, StandardOpenOption.APPEND, StandardOpenOption.CREATE)— append instead of replace, still create if missing.
Files.exists(path)— boolean check, no exception.Files.delete(path)— throwsIOException, wrap intry/catch.- All of these either need a
try/catchforIOException, orthrows IOExceptionon the enclosing method to propagate it.