How To Handle Exceptions From Static Code Block in Java Comment gérer les exceptions de statique bloc de code en Java
Exception can be handled when thrown in a method by either passing through the Exception or handling it. Exception peut être traité lorsque jeté dans une méthode ou l'autre en passant par l'exception ou la manipuler. However in a static code block how can you handle checked exceptions meaningfully? Toutefois, dans un bloc de code statique comment pouvez-vous gérer les exceptions vérifiées de façon significative?
Normally static blocks are used to execute a code only once globally (for all instances of the class). Normalement statique blocs sont utilisés pour exécuter un code qu'une seule fois, globalement (pour tous les cas de la classe). A popular example is loading the JDBC driver. Un exemple populaire charge le pilote JDBC. Sometimes the code in static block throws checked Exceptions which needs to be handled. Parfois, le code en bloc statique lance vérifié exceptions qui doivent être traitées. Simple try-catch block doesn’t do justice to the problem as normally failure in static code block means the program cannot continue. Simple essayez-bloc de capture ne rend pas justice au problème que normalement non statique en bloc de code signifie que le programme ne peut pas continuer.
A clean way to handle it is using a try-catch block. However after logging appropriate error messages you should throw a RuntimeException. Un propre façon de gérer elle utilise un try-bloc de capture. Mais après la connexion des messages d'erreur approprié, vous devriez jeter un RuntimeException. The normally ends the program execution. Le normalement fin l'exécution du programme.
Update: After logging the exception you have two options. Mise à jour: Une fois la connexion l'exception vous avez deux options. You can either throw a RuntimeException which will end the current thread (unless caught by code instantiating / calling a static method on the class for the first time) or better yet you can call System.exit(1). Vous pouvez soit lancer une RuntimeException qui prendra fin le thread courant (à moins que pris par le code instanciation / appelant une méthode statique de la classe pour la première fois) ou encore mieux, vous pouvez appeler System.exit (1). RuntimeException will end a single threaded application[Laszlo] (exception noted above). RuntimeException prendra fin une application unique filetés [Laszlo] (exception indiquée ci-dessus). In JDK 1.5 throwing RuntimeException from main thread gives a pretty descriptive message: En JDK 1,5 lancer RuntimeException de thread principal donne un joli message descriptif:
Caused by: java.lang.RuntimeException: Error! Causés par: java.lang.RuntimeException: Erreur!
at TestStaticException. à TestStaticException. (TestStaticException.java:3) (TestStaticException.java: 3)
At this point it may be argued that System.exit(1) is not desirable in a managed environment like a servlet and I agree. À ce stade, il mai faire valoir que System.exit (1) n'est pas souhaitable dans un environnement géré comme une servlet et je suis d'accord. System.exit is for java applications and only if the static initializer block performs some critical (without which the program cannot be run successfully) function like loading the database driver. System.exit est pour les applications Java et seulement si le bloc d'initialisation statique effectue certaines critiques (sans laquelle le programme ne peut pas être exécuté avec succès) comme fonction de chargement le pilote de base de données. RuntimeException may be consumed in a managed environment. RuntimeException mai être consommés dans une gestion de l'environnement. So a third option is to set a flag indicating failure. Ainsi, une troisième option consiste à fixer un drapeau indiquant l'échec. Later the constructors can check the flag and throw exceptions [Robert] or retry in rare cases. Plus tard, les constructeurs peuvent vérifier le drapeau et des exceptions [Robert] ou réessayez dans de rares cas.
If the operation is not important to the functioning of the program (like setting fonts or laf) then maybe a simple log entry is all that is required. Si l'opération n'est pas important pour le fonctionnement du programme (tels que des polices ou la mise en LAF), alors peut-être une simple inscription est nécessaire.
Filed under Classé sous Headline News Headline News , How To Comment , Java Software Logiciel de Java , Tech Note Note technique | |
| |
RSS 2.0 RSS 2,0 | |
Trackback this Article | cet article |
Email this Article Envoyer cet article
You may also like to read Vous mai également à lire |




July 6th, 2006 at 5:46 pm Juillet 6th, 2006 at 5:46 pm
That would end the thread and not program execution. Ce serait le fil fin et non l'exécution du programme. (It may result in program termination if you have only one thread.) I guess you know it, but it is more correct put this way :). (Il fait en mai programme de résiliation si vous ne disposez que d'un fil.) Je suppose que vous connaissez, mais il est plus correct de mettre cette façon:).
July 6th, 2006 at 11:57 pm Juillet 6th, 2006 at 11:57 pm
You are right. Vous avez raison. The statement is ambiguous. La déclaration est ambiguë. I will clarify it. Je vais préciser de quoi il s'agit.
July 7th, 2006 at 12:26 am 7 juillet 2006 à 12:26 am
The advice on how to handle exceptions in static blocks is actually quite dangerous. Les conseils sur la manière de gérer les exceptions dans des blocs statique est en fait très dangereux. See Voir http://twasink.net/blog/archives/2006/07/how_not_to_hand.html for more pour en savoir plus
(This would have been a trackback, but trackbacks don’t seem to show up here) (Cela aurait été un trackback, mais trackback ne semblent pas se présenter ici)
July 7th, 2006 at 8:26 am Juillet 7 mars 2006 chez 8:26 am
I have tried to address the concerns raised. J'ai essayé de répondre aux préoccupations soulevées.
July 11th, 2006 at 7:35 pm Juillet 11, 2006 at 7:35 pm
Why not throw an ExceptionInInitializerError()? Pourquoi ne pas jeter un ExceptionInInitializerError ()?
static { static (
try { try (
// do something that may throw an exception / / Faire quelque chose que mai lancer une exception
} catch (ComponentXmlException ex) { ) Catch (ComponentXmlException ex) (
throw new ExceptionInInitializerError(ex); throw new ExceptionInInitializerError (ex);
} )
} )
August 3rd, 2006 at 5:16 pm 3 août 2006 à 5:16 pm
can you send me to my email some smples of a handle exception…..plzzzzzzzzzz app or more pouvez-vous me faire parvenir mon courriel à certains smples d'un manche exception… .. plzzzzzzzzzz app ou plus
August 3rd, 2006 at 5:17 pm Août 3rd, 2006 at 5:17 pm
oh my email is Oh mon email est dielli89@hotmail.com
September 13th, 2007 at 3:21 am Septembre 13, 2007 at 3:21 am
sir i want the details of java . Monsieur je veux les détails de la technologie Java.
it is here to know about the subject of java. il est ici pour en savoir sur le sujet de Java.
so iam surfing here. de sorte maintenant surfer ici.
thankyou.