Pregunta

So I'm new at Java, and I'm trying to work with the try, catch and finally features. As my limited understanding goes, a try-catch block allows me to handle exceptions instead of the compiler throwing an error that I can't return to execution from. Is this right? Also, my program doesn't seem to be working, as the compiler throws "Extracur is abstract, cannot be instantiated!" during compilation. How do I get it to display my error message (and execute my finally block) instead?

try {
        extracur student1 = new extracur();
    } catch (InstantiationException e) {
        System.out.println("\n Did you just try to create an object for an interface? Tsk tsk.");
    } finally {
        ReportCard student = new ReportCard("Progress Report for the year 2012-13");
        student.printReportCard();
    }

PS- extracur is an interface.

¿Fue útil?

Solución

Interfaces can never be directly instantiated.

extracur student1=new extracur(); // not possible

And you should capitalize interface names. You need instead:

Extracur student1 = new Extracur() {
  // implement your methods
};

Explanation: The code does not instantiate the interface, but an anonymous inner class which implements the interface.

You should also understand that the compiler throws an error at compile time while you are trying to catch an error at runtime (too late in this case).

Otros consejos

Interface cannot be instantiated.It will cause compile error.If you want a test .Try this:

 try {
            extracur student1 = new stud();
        } catch (InstantiationException e) {
            System.out
                    .println("\n Did you just try to create an object for an interface? Tsk tsk.");
        } finally {

        }

This is a class that impements interface extracur

class stud implements extracur{
    public stud()throws InstantiationException{
        throw new  InstantiationException();
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top