Java Reference
In-Depth Information
Note If you're catching an exception in multiple catch blocks (Solution 1), make
sure that the catch blocks are defined from the most specific to the most general. Fail-
ure to follow this convention will prevent an exception from being handled by the more
specific blocks. This is most important when there are catch (Exception e)
blocks, which catch almost all exceptions.
Having a catch (Exception e) block—called a catch-all or Pokémon ® ex-
ception handler (gotta catch them all)—is usually poor practice because such a block
will catch every exception type and treat them all the same. This becomes a problem
because the block can catch other exceptions that may occur deeper within the call
stack that you may not have intended the block to catch (an OutOfMemoryExcep-
tion ). It is a best practice to specify each possible exception, rather than specifying a
catch-all exception handler to catch all exceptions.
9-5. Catching the Uncaught Exceptions
Problem
You want to know when a thread is being terminated due to an uncaught exception
such as a NullPointerException .
Solution 1
When creating a Java thread, sometimes you need to ensure that any exception is
caught and handled properly to help determine the reason for the thread termination. To
that effect, Java allows you to register an ExceptionHandler() either per thread
or globally. The following code demonstrates an example of registering an exception
handler on a per-thread basis.
private void start() {
Thread.setDefaultUncaughtExceptionHandler((Thread t,
Throwable e) -> {
System.out.println("Woa! there was an exception
thrown somewhere! "+t.getName()+": "+e);
});
Search WWH ::




Custom Search