logo

Exception arithmétique en Java

Le Exception La gestion est l'un des mécanismes les plus puissants pour gérer les erreurs d'exécution afin que le flux normal de l'application puisse être maintenu. En Java, une exception est une condition anormale. Le langage de programmation Java définit diverses exceptions. Dans cette section, nous discuterons de l'une des exceptions les plus importantes qui est ArithmétiqueException en Java.

L'exception arithmétique est un type de résultat inhabituel ou d'erreur non vérifiée du code, qui est levée ou déclenchée chaque fois qu'une opération mathématique ou arithmétique erronée apparaît dans le code pendant l'exécution. Un problème d'exécution, également appelé exception, apparaît chaque fois que le dénominateur d'une fraction est 0 et que la JVM n'est pas en mesure de connaître le résultat ; par conséquent, l'exécution du programme est terminée et une exception est levée. Notez qu'au moment où l'exception a été déclenchée, le programme se termine. Cependant, le code antérieur est exécuté et le résultat approprié est affiché.

Structure des exceptions arithmétiques

La classe de base des exceptions arithmétiques est java.lang.ArithmeticException, qui est la classe enfant de java.lang.RuntimeException, qui à son tour est la classe enfant de java.lang.Exception.

Constructeur d'exceptions arithmétiques

    ArithmétiqueException() :Il est utilisé pour définir une exception arithmétique avec zéro paramètre passé.ArithmeticException (Chaîne s) :Il est utilisé pour définir une exception arithmétique avec un paramètre passé.

Comment se produisent les exceptions arithmétiques ?

Voici deux situations dans lesquelles une exception arithmétique peut se produire.

  1. Lorsque nous effectuons une division où 0 est utilisé comme diviseur, c'est-à-dire que 0 est le dénominateur.
  2. Un nombre décimal long qui ne se termine pas par Big Decimal.

Diviser par 0

Nom de fichier: ArithmeticException.java

 public class ArithmeticException { void divide(int a, int b) { // performing divison and storing th result int res = a / b; System.out.println('Division process has been done successfully.'); System.out.println('Result came after division is: ' + res); } // main method public static void main(String argvs[]) { // creating an object of the class ArithmeticException ArithmeticException obj = new ArithmeticException(); obj.divide(1, 0); } } 

Sortir:

 Exception in thread 'main' java.lang.ArithmeticException: / by zero at ArithmeticException.divide(ArithmeticException.java:6) at ArithmeticException.main(ArithmeticException.java:16) 

Grande décimale sans fin

Nom de fichier: ArithmétiqueException1.java

 // import statement import java.math.BigDecimal; public class ArithmeticException1 { // main method public static void main(String[] argvs) { // creating two objects of BigDecimal BigDecimal a1 = new BigDecimal(11); BigDecimal a2 = new BigDecimal(17); // 11 / 17 = 0.6470588235294118... a1 = a1.divide(a2); System.out.println(a1.toString()); } } 

Sortir:

 Exception in thread 'main' java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.base/java.math.BigDecimal.divide(BigDecimal.java:1766) at ArithmeticException1.main(ArithmeticException1.java:9) 

Explication: Dans le programme ci-dessus, la classe Big Decimal ne connaît pas le résultat exact à afficher après la division. C'est parce que la sortie est une expansion décimale sans fin. Une approche pour résoudre ce problème consiste à fournir la limite. Par exemple, nous pouvons indiquer explicitement dans le programme que la sortie doit être limitée à 6 décimales. Observez le programme suivant.

Nom de fichier: ArithmétiqueException2.java

 // import statement import java.math.BigDecimal; public class ArithmeticException2 { // main method public static void main(String[] argvs) { // creating two objects of BigDecimal BigDecimal a1 = new BigDecimal(11); BigDecimal a2 = new BigDecimal(17); // 11 / 17 = 0.6470588235294118... // rounding up to decimal places a1 = a1.divide(a2, 6, BigDecimal.ROUND_DOWN); System.out.println(a1.toString()); } } 

Sortir:

 0.647058 

Gestion des exceptions arithmétiques

Nous pouvons gérer nous-mêmes l'exception arithmétique en utilisant le bloc try-catch. Observez les programmes suivants.

Nom de fichier: HandleArithmeticException.java

 public class HandleArithmeticException { void divide(int a, int b) { int res; try { // performing divison and storing th result res = a / b; System.out.println('Division process has been done successfully.'); System.out.println('Result came after division is: ' + res); } // handling the exception in the catch block catch(java.lang.ArithmeticException ex) { System.out.println('Should avoid dividing by 0 ' + ex); } } // main method public static void main(String argvs[]) { // creating an object of the class ArithmeticException ArithmeticException obj = new ArithmeticException(); obj.divide(1, 0); } } 

Sortir:

 Should avoid dividing by 0 java.lang.ArithmeticException: / by zero 

Pour une expansion décimale sans fin, tout ce que nous avons à faire est d'envelopper la ligne où la division se produit à l'intérieur du bloc try.

Nom de fichier: HandleArithmeticException1.java

 // import statement import java.math.BigDecimal; public class HandleArithmeticException1 { // main method public static void main(String[] argvs) { // creating two objects of BigDecimal BigDecimal a1 = new BigDecimal(11); BigDecimal a2 = new BigDecimal(17); try { // 11 / 17 = 0.6470588235294118... a1 = a1.divide(a2); System.out.println(a1.toString()); } // handling the exception in the catch block catch(ArithmeticException ex) { System.out.println('Should avoid dividing by an integer that leads to non-terminating decimal expansion. ' + ex); } } } 

Sortir:

 Should avoid dividing by an integer that leads to non-terminating decimal expansion. java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.