javaexception

Java throw exception cannot find symbol?


I'm trying to throw an exception from a method, but when I compile the below code:

class launcher{
public static void main(String[] args){
    try{
        getError();
        System.out.println("Line: try block");
    }catch(myException e){
        System.out.println("Line: catch block");
    }finally{
        System.out.println("Line: finally block");
    }
    System.out.println("Line: EOF main");
}
static void getError() throws myException{
        throw new myException();
    }
}

I get the following compiler error:

launcher.java:14: error: cannot find symbol
    static void getError() throws ^myException{

  symbol:   class myException

  location: class launcher

It seems as if it can't understand what is myException?


Solution

  • Problem reason and solution

    The problem is, that you haven't imported your Exception to the launcher class. Exceptions are classes so need to be declared as a typical class.

    Huge problem

    You start class names with lowercase letters which makes your class non-readable. Your classes should be called: Launcher (or better Test) and MyException instead of myException.

    You can create your own Exceptions. The following is a declaration of MyException which you might find helpful:

    MyException

    public class MyException extends RuntimeException {
        public MyException() {
            super();
        }
    }
    

    Then import your new class and you'll be able to throw it.