javaexceptiongetmessage

What is the error in my exception and the throw and getMessage?


I have code and i want to know where is the error, please can you help me: only one error on the throw line

public static void main(String[] args) {
    try {
        Scanner input = new Scanner (System.in);
        System.out.println("Enter the number ");
        int x1 = input.nextInt();
        int i;
        if (x1>=0&&x1<=100) {
            i= (int) Math.pow(x1,2);
            System.out.println("the squre of  "+ x1 + " is "+ i);
        }
        else 
            throw new MyException();   // what is the error here?
    } catch(MyException me) {
        System.out.println(me);
        String message = me.getMessage();
    }
}

public class MyException extends Exception {
 public String getMessage() {
        return " the number is out of ring";
    }
    }

}

Solution

  • First of all, your getMessage method is outside of you MyException class. Secondly, you are trying to call a method called getMessage(), which cannot be done in the main method, you have to call me.getMessage();