I am trying to catch various exceptions, but without success. When I enter a character instead of an integer an exception is thrown and the program crashes. Why doesn't it go into the catch? When I divide by 0 although the program does not fall, it does not enter the catch either System.out.println("No se puede dividir por cero!");
. Why does it not enter the catch?
import java.util.Scanner;
import java.util.InputMismatchException;
public class PROG04_ejerc5 {
public static void main(String[] args) {
boolean salir = false; //declaro variable que me permitirá salir del programa
int numdivisiones = 0;
while (!salir) {
Scanner teclado = new Scanner(System.in);
System.out.println("Escribe -1 en dividendo y en divisor para salir");
System.out.println("Introduce un número entero que será el dividendo: ");
int dividendo = teclado.nextInt(); //
System.out.println("Introduce un número entero que será el divisor: ");
int divisor = teclado.nextInt(); //
try {
float resultado = (float)dividendo / divisor;
System.out.printf("El resultado de la división es: %1.3f \n",resultado);
}catch (InputMismatchException ex) {
System.out.println("No has introducido un número entero"+ex);
}
catch (ArithmeticException e) {
System.out.println("No se puede dividir por cero!"+ e);
}finally{
System.out.println("Has realizado "+numdivisiones+" divisiones");
}
if (dividendo== -1 && divisor== -1) salir =true;
}
}
}
In the comment you have from Benito-B, he explains what happens, that
float
he does not do the same withint
.Infinity
it can even be both negative and positive.If you want to do with
float
, one way is tocatch
create your exception.Also indicate that
int numdivisiones
you have it at 0 constantly, so you will need to finish some parts of the program. Good luck and I hope I helped you.Edit: Sorry I didn't notice that you also ask for an exception when a letter is entered, that's another exception that you must indicate, since they are two different ones. Being a
InputMismatchException
, you can put another catch.The reason why you didn't miss it
catch
is because you have thetry
wrong one, you must indicate it before putting the data since Java will throw the exception immediately when having a variable with an uncontrolled exception. I have indicated it in the firstSystem.out.print
.