简体   繁体   中英

Trying to handle InstantiationException in JAVA, compiler throws it instead

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.

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM