Overriden方法不会抛出

时间:2015-04-23 02:57:11

标签: java netbeans

我在这里遇到了一些错误。我无法弄明白。 嗯。

class myException extends Exception {

    interface MyInterface {
        void myMethod () throws myException;
    }

    class MyImplementation implements MyInterface {

        @Override
        public void myMethod() throws MyException {
            System.out.println("in myMethod()");
            throw new MyException();
        }
    }

    class TheInterface { }

    public static void main(String[] args) {
        MyImplementation m;
        m = new MyImplementation();
        try {
            m.myMethod();
        } catch (MyException e) {
            System.out.println("MyException caught");
        }
    }
}

请帮忙。

3 个答案:

答案 0 :(得分:1)

您正在使用用户定义的例外但尚未创建该例外。试试这个或使用通用的例外

public class MyImplementation implements MyInterface {

    @Override
    public void myMethod() throws MyException {
        System.out.println("in myMethod()");
        throw new MyException();
    }

}

interface MyInterface {
    void myMethod () throws MyException;
}

public class MyException extends Exception {

}

public class TestThrowsException {

    public static void main(String[] args) {
        MyImplementation m = new MyImplementation();
         try {
            m.myMethod();
         } 
         catch (MyException e) {
            System.out.println("MyException caught");
         }
    }
}

通过测试方式: -

public class TestThrowsException {
    @Test(expected = MyException.class)
    public void shoudldThrowException() throws MyException {
         MyImplementation m = new MyImplementation();
         m.myMethod();
    }
}

答案 1 :(得分:0)

我认为你有错字。

interface MyInterface {
    void myMethod () throws myException; // Change it to MyException
}

还要确保正确关闭牙箍

class myException extends Exception {}

答案 2 :(得分:0)

尝试为:

class myException extends Exception {}

interface MyInterface {
void myMethod () throws myException;
}

class MyImplementation
implements MyInterface {

@Override
public void myMethod() throws myException {
    System.out.println("in myMethod()");
    throw new myException();
}
}

public class TheInterface { 
public static void main(String[] args) {
MyImplementation m;
m = new MyImplementation();
try {
m.myMethod();
} catch (myException e) {
e.printStackTrace();
        System.out.println("MyException caught");
}
}
}