Skip to content

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 try block 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 try blocks small — every statement inside is a potential jump point to a catch, so a large try block 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()) before list.get(0), instead of catching IndexOutOfBoundsException).
  • Propagation ("throw early, catch late"): instead of handling an exception right where it can occur, declare throws SomeException on 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 declare throws — 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 starting src/...).
  • Reading: Files.readAllLines(path)List<String>. Throws IOException.
  • Writing: Files.write(path, lines) — creates the file if missing, replaces its content if it exists. Throws IOException.
    • 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) — throws IOException, wrap in try/catch.
  • All of these either need a try/catch for IOException, or throws IOException on the enclosing method to propagate it.