Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet174/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   170   171   172   173   174   175   176   177   ...   245
Bog'liq
Java 17 Recipes

 How It Works
Thread.defaultUncaughtExceptionHandler() is invoked for each unchecked exception 
that has not been caught. When UncaughtExceptionHandler() handles an exception, 
it means that there was no try/catch block in place to catch the exception. As such, 
the exception bubbled up the thread stack. This is the last code executed on that thread 
before it terminates. The thread terminates when an exception is caught on either the 
thread’s or the default’s UncaughtExceptionHandler(), which logs information on the 
exception to help pinpoint the reason for the exception.
In solution 2, UncaughtExceptionHandler() is set up specifically for the current 
thread. When the thread throws an exception that is not caught, it bubbles up to 
UncaughtExceptionHandler() in the thread. If this is not present, it bubbles up to 
defaultUncaughtExceptionHandler(). Again, in either situation, the thread originating 
the exception terminates.
Tip When dealing with multiple threads, it is always good practice to explicitly 
name the threads. it makes life easier to know exactly which thread caused 
the exception, rather than having to trace down an unknown thread named like 
Thread-## (the default naming pattern of unnamed threads).
Chapter 9 exCeptions and Logging


341
9-6. Managing Resources with try/catch Blocks
 Problem
In the event of an exception, you need to ensure that any resources used within a 
try/catch block are released.
 Solution
Use the Automatic Resource Management (ARM) feature, which can be specified with 
a try-with-resources statement. When using that statement, any resources specified 
within the try clause are automatically released when the block terminates. In the 
following code, the FileOutputStream, BufferedOutputStream, and DataOutputStream 
resources are automatically handled by the try-with-resources block.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   170   171   172   173   174   175   176   177   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling