Java 17 Recipes


-5. Catching the Uncaught Exceptions


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

9-5. Catching the Uncaught Exceptions
 Problem
You want to know when a thread is terminated due to an uncaught exception such as 
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. The 
following code demonstrates registering an exception handler on a per-thread basis.
public static void main(String[] args) {
Recipe9_5 recipe = new Recipe9_5();
recipe.start();
recipe.startForCurrentThread();
}
Chapter 9 exCeptions and Logging


339
private void start() {
Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
System.out.println("Woa! there was an exception thrown somewhere! 
"+t.getName()+": "+e);
});
final Random random = new Random();
for (int j = 0; j < 10; j++) {
int divisor = random.nextInt(4);
System.out.println("200 / " + divisor + " Is " + (200 / divisor));
}
}
The following is the output.
200 / 2 Is 100
Woa! there was an exception thrown somewhere! main:
java.lang.ArithmeticException: / by zero
The for loop in this thread executes properly until an exception is encountered
when DefaultUncaughtExceptionHandler is invoked. UncaughtExceptionHandler is 
a functional interface, so utilizing a lambda expression to implement the exception 
handler is possible.
 Solution 2
It is possible to register UncaughtExceptionHandler in a specific thread. After doing 
so, any exception within the thread that has not been caught is handled by the 
uncaughtException() method. The following is an example.
private void startForCurrentThread() {
Thread.currentThread().setUncaughtExceptionHandler((Thread t, 
Throwable e) -> {
System.out.println("In this thread "+t.getName()+" an exception was 
thrown "+e);
});
Thread someThread = new Thread(() -> {
System.out.println(200/0);
});
Chapter 9 exCeptions and Logging


340
someThread.setName("Some Unlucky Thread");
someThread.start();
System.out.println("In the main thread "+ (200/0));
}
The following is the output.
In this thread main an exception was thrown java.lang.ArithmeticException: 
/ by zero
In the previous code, UncaughtExceptionHandler is registered on currentThread. As 
in solution 1, UncaughtExceptionHandler is a functional interface, so utilizing a lambda 
expression to implement the exception handler is possible.

Download 3.2 Mb.

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




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