Checked exceptions describe expected trouble from the outside world; the caller must
handle or declare them. Unchecked ones usually mean a bug.
try{vartext=Files.readString(path);}catch(IOExceptione){IO.println("cannot read: "+e.getMessage());}Stringread(Pathp)throwsIOException{// or pass it upreturnFiles.readString(p);}
try / catch / finally
try{risky();}catch(NumberFormatExceptione){// specific first…}catch(RuntimeExceptione){// general later…}finally{// always runs}
publicclassOverdraftExceptionextendsRuntimeException{privatefinallongmissing;publicOverdraftException(longmissing){super("short by %d cents".formatted(missing));this.missing=missing;}publiclongmissing(){returnmissing;}}
Always pass the cause along — otherwise you lose the information you need later:
Objects.requireNonNull(from,"from is required");if(amount<=0)thrownewIllegalArgumentException("amount must be positive: "+amount);
Situation
Exception
invalid argument
IllegalArgumentException
wrong object state
IllegalStateException
argument was null
NullPointerException via requireNonNull
not implemented yet
UnsupportedOperationException
business rule broken
your own type
Common mistakes
// swallowingtry{risky();}catch(Exceptione){}// never// control flowtry{while(true)IO.println(list.get(i++));}catch(IndexOutOfBoundsExceptione){}// use a for-each loop// useless messagesthrownewIllegalArgumentException("error");//saywhatandwhichvalue
Catch where you can actually react — usually high up, not in every helper method.
Cleanup without catching:
try{process();}finally{releaseLock();// exception still propagates}
★ Exercises
int divide(int a, int b) throwing a helpful ArithmeticException when b == 0.
Write InvalidInputException and use it in a validator.
A method returning an empty list instead of throwing when a file is missing — when is that
good, when dangerous?
<T> T withRetry(Supplier<T> task, int attempts) — retry on exception, rethrow the last one.
Create a wrapped exception (cause + wrapper) and print both messages.
What does a method return when try has return 1 and finally has return 2? Try it —
then never write it.