Need some references for Constructor with Exceptions
Davie Lin
Ranch Hand
Joined: Aug 05, 2007
Posts: 294
posted
0
Hi people, I was trying to learn the iText api and was noticing creating the pdf document object's constructor throws exceptions.
I have not read any code before that constructors throws exceptions and I am sure that pdf type of object must be risky to create so it throws exceptions to let you know the program didn't make it.
At this point, I am guessing that this is legal to do in Java and it follow most of the exception rule with methods which means it must be wrap in a try/catch block when you instantiate this object. I been reading SCJP from K & B but didn't see anything talking about my subject of interest. So if anyone have reference about constructor with exceptions and can post them would be much appreciated.
I'm not sure what you want to know--constructors can throw exceptions just like any other method; there's nothing special about it. For example, the java.io.FileWriter constructor throws an exception if the file can't be opened.
Muhammad Khojaye
Ranch Hand
Joined: Apr 12, 2009
Posts: 341
posted
0
As per JLS
A compiler for the Java programming language checks, at compile time, that a program contains handlers for checked exceptions, by analyzing which checked exceptions can result from execution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method (§8.4.6) or constructor (§8.8.5) must mention the class of that exception or one of the superclasses of the class of that exception
Davie Lin
Ranch Hand
Joined: Aug 05, 2007
Posts: 294
posted
0
Cool, so the exception for constructor follows the same rule as exception for methods, that's all I wanted to know. I raise this question because I have not seen any code from real life nor any of my books, so I wasn't sure if exception for constructor follows the same rule as methods or it has a different set of rules it follows or what not.
Anyways, thanks for clarify for me
Ernest Friedman-Hill
author and iconoclast
Marshal
The one thing to realize -- and it's an important thing! -- is that if a constructor throws an exception, then the "new" expression doesn't return, and therefore most of the time, the object effectively is not created. This is a good thing -- it lets you abort object creation if you don't have enough data to construct a valid object, for example.
Now, I said "most of the time" and "as if" because the object actually is created, and you can arrange to actually use it after a constructor aborts. Look at this (BAD!) code:
The constructor stores a reference to the object, then aborts with an exception. But that stored reference remains: the partially constructed object lives on, and the println() shows it. Make sure you never, ever write code like this!