Java 17 Recipes
-5. Catching the Uncaught Exceptions
Download 3.2 Mb. Pdf ko'rish
|
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: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling