


Comment utiliser la gestion des exceptions Java UncaughtExceptionHandler
Gestion des exceptions
Exception de thread non interceptée UncaughtException nécessite la gestion d'UncaughtZExceptionHandler
Alors pourquoi devez-vous utiliser UncaughtZExceptionHandler ?
Le thread principal peut facilement capturer le thread, mais le sous-thread ne le peut pas
Comme vous pouvez le voir dans le code ci-dessous, même si le sous-thread lève une exception, le thread principal ne sera pas affecté à all
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 * */
Comme vous pouvez le voir dans le code ci-dessous, même s'il est inutile d'utiliser catch pour intercepter les exceptions de sous-thread
essayez catch pour le thread principal, il n'y a aucun moyen d'attraper le sous-thread -thread exceptions
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 * */
Les exceptions peuvent être interceptées par try catch dans la méthode d'exécution, mais particulièrement gênantes, car vous devez essayer manuellement catch dans chaque méthode d'exécution
UncaughtExceptionHandler
Personnaliser 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); } }
Utilisez une classe personnalisée pour attraper des 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 * */
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Outils d'IA chauds

Undress AI Tool
Images de déshabillage gratuites

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Clothoff.io
Dissolvant de vêtements AI

Video Face Swap
Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Article chaud

Outils chauds

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

CheckkSearchSettings like "MatchEnteRireCellContents" et "MatchCase" ByExpandingOptionsInFindanDreplace, garantissant "lookin" issettominuesand »dans" TOCORRECTSCOPE; 2.LOORHFORHIDDENCHARACTER

Thebestjavaidein2024Denpendyourndeds: 1.chooseintellijideaforprofessional, l'entreprise, le development orfulldevelopmentduetoitsSuperiorCodeIntelligence, le framewory

Tout d'abord, Checkif "ClearbrowsingDataOnClose" IsTurneDOninsettingsandTurnitofftoenSureHistoryissaved.2.Confirmyou'renotusingInprivateMode, asitdoesNotsAvehistoryByDesigr.3.Disable ExtensionStendatoryToUleoutHeleft

Préparez-vous en application par rapport à Mavenorgradletobuildajarorwarfile, externalisationConfiguration.2.ChoOSEADPLOYENDIRONMENT: Runonbaremetal / vmwithjava-jarandsystemd, deploywarontomcat, compeneriserisewithdocker, orusecloudplatformslikelise.

L'utilisation de SLF4J combinée avec la journalisation ou le log4j2 est le moyen recommandé de configurer les journaux dans les applications Java. Il introduit des bibliothèques API et implémentation en ajoutant des dépendances Maven correspondantes; 2. Obtenez l'enregistreur via le loggerfactory de SLF4J dans le code et écrivez le code journal découplé et efficace à l'aide de méthodes de journalisation paramétrée; 3. Définir le format de sortie du journal, le niveau, la cible (console, le fichier) et le contrôle du journal du package via Logback.xml ou les fichiers de configuration log4j2.xml; 4. Activer éventuellement la fonction de balayage de fichiers de configuration pour atteindre un ajustement dynamique du niveau de journal, et Springboot peut également être géré via des points de terminaison de l'actionneur; 5. Suivez les meilleures pratiques, y compris

CASTORENablesxml-to-javaObjectMappingViadefaultConverionsOrexplicitMappingFiles; 1) DefinejavaclasseswithGetters / seters; 2) useUnmarShallertOConvertXmltoObjects; 3)

Dans JavaScript, la méthode la plus courante pour ajouter des éléments au début d'un tableau est d'utiliser la méthode Unsich (); 1. En utilisant unsith () modifiera directement le tableau d'origine, vous pouvez ajouter un ou plusieurs éléments pour retourner la nouvelle longueur du tableau ajouté; 2. Si vous ne souhaitez pas modifier le tableau d'origine, il est recommandé d'utiliser l'opérateur d'extension (tel que [Newelement, ... Arr]) pour créer un nouveau tableau; 3. Vous pouvez également utiliser la méthode CONCAT () pour combiner le nouveau tableau d'éléments avec le numéro d'origine, renvoyez le nouveau tableau sans modifier le tableau d'origine; En résumé, utilisez Unsich () lors de la modification du tableau d'origine et recommandez l'opérateur d'extension lorsque vous gardez le tableau d'origine inchangé.

GOTYPICAL OFFERSBETTERRUNTIMEPERFORMANCE AVEC LA MAINTRÉE DE PUTHROUGHTANDLOWERLATENCE, ENTERTFORI / O-HEAVYSERVICES, DUETOITSLIGHT LONDEGOROUTINESANDERFICENTSCHEDULL
