Try and catch exception handling help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Try and catch exception handling help

so basically try and catch in exception handling is to inform the user if they have keyed in the wrong data right?for example,my code below only accepts true and false input.so if u key in a number,the catch block will tell the user their exact error.am i doing it correctly? https://code.sololearn.com/cU0a0V9qPzC9/?ref=app

3rd Nov 2017, 10:37 AM
oyl
8 Answers
+ 6
you should use an if statement. if(input.equalsIgnoreCase("True"){System.out.println("True");} else{System.out.println("false");
3rd Nov 2017, 7:24 PM
D_Stark
D_Stark - avatar
+ 5
hmm.. do u mean if the input is true print true and if the input is a number catch it and print false?
3rd Nov 2017, 6:00 PM
D_Stark
D_Stark - avatar
+ 4
i think the problem you have with this is that the try dosent really know what its ment to be catching try this which scanner is assigned to a interger input. import java.util.Scanner; public class MyClass { public static void main(String[ ] args) { boolean boo = true; try { Scanner x=new Scanner(System.in); int i = x.nextInt(); System.out.println(boo); } catch (Exception e) { System.out.println(!boo); } } }
3rd Nov 2017, 11:41 AM
D_Stark
D_Stark - avatar
+ 3
yes as the string input is not equal to "true" so it will fall to the else statement
4th Nov 2017, 8:49 AM
D_Stark
D_Stark - avatar
0
doesnt "System.out.println(x.nextBoolean());" tell the program that it only accepts only true or false input?
3rd Nov 2017, 4:41 PM
oyl
0
if you input a number,it will prompt the user that " "please key in true or false".doesnt it make sense?
3rd Nov 2017, 6:02 PM
oyl
0
does it show an error if i type in rubbish like /_×€×€×&&× ?; using your if else code?
3rd Nov 2017, 7:27 PM
oyl
- 1
it will prompt the user "please key in true or false" whatever rubbish the user key in "#%$_/_¥"'%("€". unless you type true or false
3rd Nov 2017, 6:08 PM
oyl