This is the example. Taschenrechner just means calculator.
This is the main class:
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
try {
Taschenrechner.divide(num1,num2);
}
catch (Exception e) {
System.out.println("Wrong entry repeat your entry");
num1 = sc.nextInt();
num2 = sc.nextInt();
try {
Taschenrechner.divide(num1,num2);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
This is the Taschenrechner class with the class method:
public static void divide(int userZahl1, int userZahl2) throws Exception {
if(userZahl2 == 0) {
throw new Exception();
}
else {
System.out.println("Ergebnis : " + (userZahl1/userZahl2));
}
}
}
What I don't get is why I have to wrap the second Taschenrechner.divide() method, within the catch block, in another try/catch block?
In general I don't quite understand why I use the throw/throws and try and catch in Java?
Is it really the more efficient way to handle errors instead of if clauses like
if(userEntry == 0 ){ System.out.println("Wrong entry. Try again!"); } ?