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

4th Nov 2021, 10:36 PM
Kakai
Kakai - avatar
4 ответов
+ 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).
5th Nov 2021, 12:08 AM
Ipang
+ 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"); }
5th Nov 2021, 12:34 AM
zemiak
+ 2
Ipang yeh i forgot to put but still looping the error.
5th Nov 2021, 4:40 AM
Kakai
Kakai - avatar
+ 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
6th Nov 2021, 4:47 AM
Ashif
Ashif - avatar