-3

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";
    }
    }

}

2 Answers2

0

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();

Moddl
  • 360
  • 3
  • 13
0

It looks like you haven't quite posted your entire class, but based on the error message it looks like MyException occurs inside your class, something like:

public class TheClass {

    public static void main(String[] args) {
        ....
    }

    public class MyException extends Exception {
        ....
    }

}

This makes MyException an inner class. Every instance of MyException must therefore "belong" to an instance of TheClass. That's why you get the "non-static variable this" error message. When you say new MyException, you're inside the static main method, so it has no way of knowing what instance of TheClass the new MyException object will belong to.

I don't think you want this to be an inner class. Either move MyException outside of TheClass, or make it static:

public static class MyException extends Exception {

Making it static would make it a "nested" rather than an "inner" class, so that it doesn't belong to an instance of TheClass. You probably want to move it outside, though. I don't see a good reason for it to be in your other class.

ajb
  • 31,309
  • 3
  • 58
  • 84