Command Palette

Search for a command to run...

Back to the lesson: Topic 7.8 — Exception Best Practices and Helpful NullPointerExceptions
Core Java · Example 2 of 3

Swallowing vs reporting with context

The bad version also silently dropped ' 80' (a leading space), so its total is wrong in a way nobody would notice.

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.

01

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".

02

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.

03

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

01

Why is swallowing exceptions dangerous, and what should a catch block do instead?

02

What are helpful NullPointerException messages, and when do they show <local1>?

03

Where in an application should exceptions be caught and logged?

04

When should a method return Optional instead of throwing an exception?

05

List the exception-handling rules you would check in a code review.

Swallowing vs reporting with context
Sign in to run this example in your browser.

Expected output

bad total: 165
rejected: 2 bad prices: [line 3: '9O' is not a price, line 5: '' is not a price]
good total: 245