0
Java try and catch - error
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int p = 0; while (true) { try { System.out.print("Enter num: "); p = input.nextInt(); } catch (Exception e) { System.out.println("Error"); } } } } Why does when catch block gets infinite loop when its triggered? I am pretty sure in python this ganna work because this is how i make error handling. Thankssssss
5 Answers
+ 3
I don't see any `break` statement, is that the complete code? I think loops do not stop unless its exit condition was satisfied, or a `break` statement was issued (same goes for Python).
+ 2
by catch, code normally continue after catch block
if you want read numbers till user sends something other, do
try {
while (true) {
System.out.print("Enter num: ");
p = input.nextInt();
}
} catch (Exception e) {
System.out.println("Error");
}
+ 2
Ipang yeh i forgot to put but still looping the error.
+ 1
Add the break statment after the System.out.println("Error")
So, control can move out from the loop.
Code:-
https://code.sololearn.com/cm5QEAEmXXjB/?ref=app