Estou aprendendo um pouco sobre exceções, e estava estudando o seguinte código:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ifet.telematica.Exceção;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Classe teste para exemplificar Exception.
* @author Emanuel Sena
*/
public class DivideByZeroExceptionHandling {
public static int quotient(int numerador, int denominador)
throws ArithmeticException
{
return numerador/denominador;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean continueLoop = true;
do{
try{
System.out.println("Please enter an integer numerator: ");
int numerator = scanner.nextInt();
System.out.println("Please enter an denominator: ");
int denominator = scanner.nextInt();
int result = quotient(numerator, denominator);
System.out.printf("\nResult: %d / %d = %d\n",
numerator, denominator, result);
continueLoop = false;
}catch( InputMismatchException e ){
System.err.printf("\nException: %s\n", e);
scanner.nextInt();
System.out.println("You must enter integer. Please try again.\n");
}catch(ArithmeticException e){
System.err.printf("\nException: %s\n", e);
System.out.println(
"Zero is a invalid denominator. Please try again.\n");
}
}while(continueLoop);
}
}
No tratamento do erro InputMismatchException, a partir da linha 37, acontece exatamente o erro q deveria ser tratado:
Exception: java.util.InputMismatchException
Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at ifet.telematica.Exceção.DivideByZeroExceptionHandling.main(DivideByZeroExceptionHandling.java:39)
Java Result: 1
Se eu retirar a linha 37: scanner.nextInt();
o programa entra em um loop infinito até estourar a pilha.
Desde já agradeço a resolução desse problema.
[i]Emanuel Dário[/i]