Re: Returning an object
- From: Patricia Shanahan <pats@xxxxxxx>
- Date: Tue, 20 Feb 2007 15:10:52 GMT
mikew01 wrote:
Hi, I am after some advice regarding returning an object called for in
one class and constructed in another.
The class that constructs the object has around ten methods that if
successful will all be called during creation of the object however
each method could throw an exception due to IO errors so I was
wondering how do you code something like this.
The calling class currently calls a single method in the creation
class which in turn makes calls to another method and so on until the
object is built, this is fine if all goes well but how do you deal
with an exception.
If an exception is thrown the object will not be built and the calling
class will have no object to deal with.
I guess you can use boolean return values for each method in the
creation class and return null or another sensible value to the caller
if something goes wrong but this seems clunky.
Why not throw an exception to the class that wanted the object if the
object cannot be built?
Look closely at the inter-class interface. Does the caller know about
the IO activities? If so, it may make sense to just let the IO
exceptions flow back to the caller.
In other cases, the caller does not know or care about IO. Then you
could define an exception of your own that explains the failure to
create the object in terms that make sense for that interface. You can
pass the IO exception to the Exception constructor so that no
information is destroyed.
The caller's code becomes:
try{
SomeType o = interfaceMethod.result();
// do things with o
}catch(YourExceptionWhatever e){
// deal with not having o.
}
Patricia
.
- References:
- Returning an object
- From: mikew01
- Returning an object
- Prev by Date: Re: Returning an object
- Next by Date: Re: Help me!! Why java is so popular
- Previous by thread: Re: Returning an object
- Next by thread: Re: Returning an object
- Index(es):
Relevant Pages
|