Hello,
I do not understand what is wrong in my code. I am trying to catch negative values, but the program is just running as normal, accepting them.
package perfectSquareException2; import java.lang.*; import java.util.Scanner; public class perfSqEx { public static void main(String args[] ) { Scanner in= new Scanner(System.in); double number = 0; double a = 0; boolean square = true; boolean correct = false; System.out.println("Enter positive number: "); try { number = in.nextDouble(); if (number > 0) correct = true; }catch (Exception exception) { if (number < 0) System.err.println(exception.getMessage() + "\n"); } if((Math.sqrt(number) * 10) % 10 == 0.0 ) { square = true; System.out.println("yes"); }else { square = false; System.out.println("no"); } } }
--- Update ---
I know that I can create my own exception that will inherit general Exceptions class. Bt in this task I have to use exactly try catch block with the exception of type Exception.