How to use Java exception handling UncaughtExceptionHandler
Exception handling
Thread uncaught exception UncaughtException requires UncaughtZExceptionHandler for processing
So why do you have to use UncaughtZExceptionHandler?
The main thread can easily capture the thread, but the sub-thread cannot
As can be seen from the following code, even if the sub-thread throws an exception, the main thread will not Unaffected
public class ChildException implements Runnable{ public static void main(String[] args) { new Thread(new ChildException()).start(); for (int i = 0; i < 10; i++) { System.out.println(i); } } @Override public void run() { throw new RuntimeException(); } } /* * Exception in thread "Thread-0" java.lang.RuntimeException at com.jx.JavaTest.Thread.Exception.ChildException.run(ChildException.java:14) at java.lang.Thread.run(Thread.java:748) 0 1 2 3 4 5 6 7 8 9 * */
As can be seen from the code below, even if you want to use catch to capture child thread exceptions, it is useless
try catch is for the main thread, there is no way to catch the exception of the sub-thread
public class CantCatch implements Runnable { public static void main(String[] args) throws InterruptedException { try { new Thread(new CantCatch(), "thread0").start(); Thread.sleep(300); new Thread(new CantCatch(), "thread1").start(); Thread.sleep(300); new Thread(new CantCatch(), "thread2").start(); Thread.sleep(300); new Thread(new CantCatch(), "thread3").start(); Thread.sleep(300); } catch (RuntimeException e) { System.out.println("catch"); } } @Override public void run() { throw new RuntimeException(); } } /* * Exception in thread "thread0" java.lang.RuntimeException at com.jx.JavaTest.Thread.Exception.CantCatch.run(CantCatch.java:22) at java.lang.Thread.run(Thread.java:748) Exception in thread "thread1" java.lang.RuntimeException at com.jx.JavaTest.Thread.Exception.CantCatch.run(CantCatch.java:22) at java.lang.Thread.run(Thread.java:748) Exception in thread "thread2" java.lang.RuntimeException at com.jx.JavaTest.Thread.Exception.CantCatch.run(CantCatch.java:22) at java.lang.Thread.run(Thread.java:748) Exception in thread "thread3" java.lang.RuntimeException at com.jx.JavaTest.Thread.Exception.CantCatch.run(CantCatch.java:22) at java.lang.Thread.run(Thread.java:748) Process finished with exit code 0 * */
Exceptions can be caught by try catch in the run method, but it is particularly troublesome because it needs to be done manually Try catch in each run method
UncaughtExceptionHandler
Custom UncaughtExceptionHandler
public class MyUncaughtHandler implements Thread.UncaughtExceptionHandler{ private String name; public MyUncaughtHandler(String name) { this.name = name; } @Override public void uncaughtException(Thread t, Throwable e) { Logger logger = Logger.getAnonymousLogger(); logger.log(Level.WARNING, "线程异常" + t.getName(), e); System.out.println(name + "捕获" + t.getName()+ e); } }
Use a custom class to catch exceptions
public class UseOwnExceptionHandler implements Runnable { public static void main(String[] args) throws InterruptedException { Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtHandler("MyHandler")); // try { new Thread(new UseOwnExceptionHandler(), "thread0").start(); Thread.sleep(300); new Thread(new UseOwnExceptionHandler(), "thread1").start(); Thread.sleep(300); new Thread(new UseOwnExceptionHandler(), "thread2").start(); Thread.sleep(300); new Thread(new UseOwnExceptionHandler(), "thread3").start(); Thread.sleep(300); // } catch (RuntimeException e) { // System.out.println("catch"); // } } @Override public void run() { // try { throw new RuntimeException(); // } catch (RuntimeException e) { // System.out.println("e"); // } } } /* * 一月 29, 2023 11:22:01 上午 com.jx.JavaTest.Thread.Exception.MyUncaughtHandler uncaughtException 警告: 线程异常thread0 java.lang.RuntimeException at com.jx.JavaTest.Thread.Exception.UseOwnExceptionHandler.run(UseOwnExceptionHandler.java:24) at java.lang.Thread.run(Thread.java:748) MyHandler捕获thread0java.lang.RuntimeException 一月 29, 2023 11:22:01 上午 com.jx.JavaTest.Thread.Exception.MyUncaughtHandler uncaughtException 警告: 线程异常thread1 java.lang.RuntimeException at com.jx.JavaTest.Thread.Exception.UseOwnExceptionHandler.run(UseOwnExceptionHandler.java:24) at java.lang.Thread.run(Thread.java:748) MyHandler捕获thread1java.lang.RuntimeException 一月 29, 2023 11:22:02 上午 com.jx.JavaTest.Thread.Exception.MyUncaughtHandler uncaughtException 警告: 线程异常thread2 java.lang.RuntimeException at com.jx.JavaTest.Thread.Exception.UseOwnExceptionHandler.run(UseOwnExceptionHandler.java:24) at java.lang.Thread.run(Thread.java:748) MyHandler捕获thread2java.lang.RuntimeException 一月 29, 2023 11:22:02 上午 com.jx.JavaTest.Thread.Exception.MyUncaughtHandler uncaughtException 警告: 线程异常thread3 java.lang.RuntimeException at com.jx.JavaTest.Thread.Exception.UseOwnExceptionHandler.run(UseOwnExceptionHandler.java:24) at java.lang.Thread.run(Thread.java:748) MyHandler捕获thread3java.lang.RuntimeException Process finished with exit code 0 * */
The above is the detailed content of How to use Java exception handling UncaughtExceptionHandler. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
