GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Exception Handling — java.evolved

Home / Topics / Exception Handling
🏷 Exception Handling 5 patterns

Topic: Exception Handling

All Java patterns related to Exception Handling — java.evolved

I/O

Try-with-resources improvement

Old Connection conn = getConnection(); // Must re-declare in try try (Connection c = conn) { use(c); }
Modern Connection conn = getConnection(); // Use existing variable directly try (conn) { use(conn); }
hover to see modern →
JDK 9+ learn more →
Errors

Helpful NullPointerExceptions

Old // Old NPE message: // "NullPointerException" // at MyApp.main(MyApp.java:42) // Which variable was null?!
Modern // Modern NPE message: // Cannot invoke "String.length()" // because "user.address().city()" // is null // Exact variable identified!
hover to see modern →
JDK 14+ learn more →
Errors

Multi-catch exception handling

Old try { process(); } catch (IOException e) { log(e); } catch (SQLException e) { log(e); } catch (ParseException e) { log(e); }
Modern try { process(); } catch (IOException | SQLException | ParseException e) { log(e); }
hover to see modern →
JDK 7+ learn more →
Errors

Optional.orElseThrow() without supplier

Old // Risky: get() throws if empty, no clear intent String value = optional.get(); // Verbose: supplier just for NoSuchElementException String value = optional .orElseThrow(NoSuchElementException::new);
Modern // Clear intent: throws NoSuchElementException if empty String value = optional.orElseThrow();
hover to see modern →
JDK 10+ learn more →
Tooling

Class.newInstance() to constructor reflection

Old Plugin plugin = pluginClass.newInstance();
Modern Plugin plugin = pluginClass .getDeclaredConstructor() .newInstance();
hover to see modern →
JDK 9+ learn more →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.