File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can constructor throw exception?

 
Jason Wang
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came across this question:
which of the following statements are true about constructor?
1. a class inherits its constructor from its parent class
2. a constructor may have a return type
3. a constructor may throw exception
4. compiler will assign a default constructor if a class does not explicitly declare one.
I chose 4 only, but the answer is 3 and 4. but when I read Khalid books, it clearly say constructor can not throw exceptions. Do I have a real bad memory?
Second question about constructor, I know it has been discussed before, but I want to clarify my confusion.
Because some books say, constructor can be defined final, but Khalid book again claims that there is no other modifiers permitted except accessibility modifier preceding constructor.
Any body step out to shed some light on this?
 
Fred Abbot
Ranch Hand
Posts: 300
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi i dont know about hte modifiers but i am pretty sure i reda somewhere that a constructer can throw an exception and it makes sense since you can do everything in a constructor there will be exceptions you will have to throw
 
Ram Nath
Greenhorn
Posts: 29
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors can throw exceptions.
 
Sandra Marti
Ranch Hand
Posts: 63
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason,
For your question 'can constructors be declared final?', this should clear your doubts.
 
Shafeeq Sheikh
Ranch Hand
Posts: 68
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors can definitely throw exceptions.....
As for them being final, the RHE and Exam Cram books clearly mention that they cannot be final, static, volatile or transient. At the same time they can be private, protected or public.
 
Ranjan Sarangi
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Shafeeq Sheikh that Constructors can definitely throw exceptions. One precaution there...
Per Bruce Eckel (TIJ, P-392) -
If your class is a derived class then its constructor must declare any base-class constructor exceptions in its exception specification.
Because a base-class constructor will always be called one way or another.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and you can't put it inside a try loop, though you might want to.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic