Quelle est la différence entre lancer Vs. jette en Java
Publié: 2013-07-23L'un le déclare et l'autre le fait
Il existe cinq mots-clés liés à la gestion des exceptions en Java, par exemple try, catch, finally, throw et throws . Outre la différence entre final, finally et finalize , throw vs throws est l'une des questions d'entretien Java les plus fréquemment posées.
- throw Le mot-clé est utilisé pour lancer une exception à partir de n'importe quelle méthode ou bloc statique en Java tandis que throws mot-clé , utilisé dans la déclaration de méthode, indique quelle exception peut être levée par cette méthode. Ils ne sont pas interchangeables.
- Si une méthode lève une exception cochée comme indiqué dans l'exemple ci-dessous, l'appelant peut soit gérer cette exception en l'attrapant, soit la relancer en déclarant une autre clause throws dans la déclaration de méthode.
- La clause Throw peut être utilisée dans n'importe quelle partie du code où vous pensez qu'une exception spécifique doit être levée à la méthode appelante.
Comprendre les exceptions Java :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
java . lang . Object | +-- java . lang . Throwable | +-- java . lang . Exception | | | +-- java . lang . ClassNotFoundException | | | +-- java . io . IOException | | | | | +-- java . io . FileNotFoundException | | | +-- java . lang . RuntimeException | | | +-- java . lang . NullPointerException | | | +-- java . lang . IndexOutOfBoundsException | | | +-- java . lang . ArrayIndexOutOfBoundsException | +-- java . lang . Error | +-- java . lang . VirtualMachineError | +-- java . lang . OutOfMemoryError |
Si une méthode lève une exception, elle doit soit être entourée d'un bloc try catch pour l'attraper, soit cette méthode doit avoir la clause throws dans sa signature. Sans la clause throws dans la signature, le compilateur Java JVM ne sait pas quoi faire de l'exception. La clause throws indique au compilateur que cette exception particulière sera gérée par la méthode appelante.
Vous trouverez ci-dessous un exemple très simple qui explique le comportement du bloc Throw, Throws, Try, Catch, Enfin en Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package com . crunchify . tutorials ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; /** * @author Crunchify.com */ public class CrunchifyThrowThrows { @SuppressWarnings ( "unused" ) public static void main ( String args [ ] ) throws Exception { FileInputStream crunchifyStream1 = null ; FileInputStream crunchifyStream2 = null ; String fileName = "Crunchify.txt" ; System . out . println ( "main: Starting " + CrunchifyThrowThrows . class . getName ( ) + " with file name = " + fileName ) ; // get file input stream 1 try { crunchifyStream1 = crunchifyTest1 ( fileName ) ; } catch ( FileNotFoundException ex ) { System . out . println ( "main: Oops, FileNotFoundException caught" ) ; } catch ( Exception ex ) { System . out . println ( "main: Oops, genreal exception caught" ) ; } // get file input stream 2 crunchifyStream2 = crunchifyTest2 ( fileName ) ; System . out . println ( "main: " + CrunchifyThrowThrows . class . getName ( ) + " ended" ) ; } public static FileInputStream crunchifyTest1 ( String fileName ) throws FileNotFoundException { FileInputStream crunchifyStream = new FileInputStream ( fileName ) ; System . out . println ( "crunchifyTest1: File input stream created" ) ; return crunchifyStream ; } public static FileInputStream crunchifyTest2 ( String fileName ) throws Exception { FileInputStream crunchifyStream = null ; try { crunchifyStream = new FileInputStream ( fileName ) ; } catch ( FileNotFoundException ex ) { throw new Exception ( "crunchifyTest2: Oops, FileNotFoundException caught" ) ; //System.out.println("crunchifyTest2: Oops, FileNotFoundException caught"); } finally { System . out . println ( "crunchifyTest2: finally block" ) ; } System . out . println ( "crunchifyTest2: Returning from crunchifyTest2" ) ; return crunchifyStream ; } } |
Résultat:

1 2 3 4 5 6 |
main : Starting com . crunchify . tutorials . CrunchifyThrowThrows with file name = Crunchify . txt main : Oops , FileNotFoundException caught crunchifyTest2 : finally block Exception in thread "main" java . lang . Exception : crunchifyTest2 : Oops , FileNotFoundException caught at com . crunchify . tutorials . CrunchifyThrowThrows . crunchifyTest2 ( CrunchifyThrowThrows . java : 45 ) at com . crunchify . tutorials . CrunchifyThrowThrows . main ( CrunchifyThrowThrows . java : 30 ) |
Maintenant, remplacez simplement les lignes 45 et 46 par la ligne ci-dessous pour voir le résultat ci-dessous :
1 2 |
//throw new Exception("crunchifyTest2: Oops, FileNotFoundException caught"); System . out . println ( "crunchifyTest2: Oops, FileNotFoundException caught" ) ; |
Nouveau résultat :
1 2 3 4 5 6 |
main : Starting com . crunchify . tutorials . CrunchifyThrowThrows with file name = Crunchify . txt main : Oops , FileNotFoundException caught crunchifyTest2 : Oops , FileNotFoundException caught crunchifyTest2 : finally block crunchifyTest2 : Returning from crunchifyTest2 main : com . crunchify . tutorials . CrunchifyThrowThrows ended |
Liste de tous les tutoriels Java qui pourraient vous intéresser.
Conseils bonus sur les exceptions :
- L'exécution normale du programme est immédiatement branchée lorsqu'une exception est levée.
- Les exceptions cochées doivent être interceptées ou transmises. Cela peut être fait dans une instruction try … catch ou en définissant l'exception dans la définition de la méthode.
- L'exception est interceptée par le premier bloc catch dont la classe d'exception associée correspond à la classe ou à une superclasse de l'exception levée.
- Si aucun bloc catch correspondant n'est trouvé dans la chaîne d'exceptions, le thread contenant l'exception levée est terminé.
- Le bloc finally après une instruction try … catch est exécuté, qu'une exception soit interceptée ou non.
- Le retour dans un bloc finally rompt la chaîne d'exceptions vers l'invocateur, même pour les exceptions non interceptées.