Expected absence in the type, real failures as exceptions
Good exception handling means failing fast with clear messages, catching only what you can handle, never swallowing errors, keeping causes, closing resources and logging once. Since Java 14, NullPointerException messages also say exactly which value was null.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Rewrite static int port(String s) { try { return Integer.parseInt(s); } catch (Exception e) { return 0; } } so that a blank string means the default 8080, anything unparsable throws IllegalArgumentException with the value and the cause, and ports outside 1..65535 are rejected. Test with "", "9000", "90x" and "70000".
Write a tiny top-level loop over three tasks (Runnables): one succeeds, one throws IllegalStateException("disk full") wrapped as the cause of RuntimeException("task 2 failed"), and one succeeds. Print done/FAILED per task with the root cause message, and make sure the loop continues.
Write static Optional<String> cityOf(Map<String, String> addresses, String user) and use it to print city: Pune for a known user and city: unknown for an unknown one, with no null checks in main.
Explain it without notes
Why is swallowing exceptions dangerous, and what should a catch block do instead?
What are helpful NullPointerException messages, and when do they show <local1>?
Where in an application should exceptions be caught and logged?
When should a method return Optional instead of throwing an exception?
List the exception-handling rules you would check in a code review.
Expected output
samosa in stock? false
tea stock: 12
reserved 2 tea
cannot reserve: only 0 cake left, asked 1
cannot reserve: unknown item: samosa