Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

java - Why default constructor cannot handle exception type Exception?

I want to know that why i have to define an explict constructor because i am getting error which says that default constructor cannot handle exception type Exception thrown by implicit super constructor.

class A {
    A() throws Exception {
        System.out.println("A Class");
    }
}

public class Example extends A {
    public static void main(String args[]) throws Exception {
        Example t = new Example();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes - your Example class is effectively declaring:

public Example() {
    super();
}

That won't compile, because the super() call is calling the A() constructor which is declared to throw Exception, which is a checked exception. That's just as much a mistake in a constructor as it is to call a method which declares that it throws a checked exception from within a method which neither catches the exception nor declares that it throws it itself.

So you need to declare the exception in an explicitly declared constructor in Example.

public Example() throws Exception {
    super(); // This is implicit; you can remove it if you want.
}

instead. Note that this is only relevant if the constructor throws a checked exception... unchecked exceptions don't need to be declared, so the "compiler-provided" default exception is fine.

Also note that you can't catch an exception thrown by a super-constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...