It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exceptions" Watch "Exceptions" New topic



Joined: Nov 05, 2000
Posts: 2
Can anybody tell if Constructors can throw exceptions.
Thanks for ur time
Mapraputa Is
Leverager of our synergies

Joined: Aug 26, 2000
Posts: 10065
Gayathri, answering your question: yes, constructors can throw exceptions, you can see an example here.
Also, may I ask you to register with proper name?
You can read this post for more details. We are glad to see you here, just a little formality´┐Ż

Uncontrolled vocabularies
"I try my best to make *all* my posts nice, even when I feel upset" -- Philippe Maquet

Joined: Nov 05, 2000
Posts: 2
hello Mapraputa Is
Thanks for ur help.I do consider ur suggestion.
yogesh sood
Ranch Hand

Joined: Aug 31, 2000
Posts: 108
Yes constructor can always Throw exception
class MyEx1 extends Exception{}
class MyEx2 extends Exception{}
class My extends Exception{}
class B{
B() throws MyEx1,My{}

class A extends B{
//A()throws MyEx2,My{ } //Compiler error line 4
A()throws MyEx2,Myex1,My{ }
public static void main(String args[]){
new A();
}catch(Exception e){}

This was simple case now come to class hiearchy

Derivedclass constructor can throw any exception regrad less of what base class throws.
Since Base Class Constructor is always called directly or indirectly
the derived-class constructor must declare any base-class constructor exceptions in its exception specification. Note that a derived-class constructor cannot catch exceptions thrown by its base-class constructor.
This is way commented constructor in code gives error coz it does not handle all exception throw by base class constructor.

In simple language Rule for Constructors is that
constructor can throw any exception regradless of base class constructor as long it is handling exception thrown by Super class.

But rule is not same for overriding methods.

a overidden method cannot throw exception which is not thrown by superclass method however it can choose to throw either no exception or any subclass of exception Which is throwm by superclass or that exception itself.

u can check this try to write code based upon two rules.

Note : in this topic when im talking bout exception they are checked exception coz unchecked exception never gives compile time error as they never checked by compiler.
Hope this will Help

If its green its biology if its stinkks its chemistry if it has numbers it is Maths and if it doesn't work its TECHNOLOGY
I agree. Here's the link:
subject: Exceptions
It's not a secret anymore!