Hello everyone,


When exceptions occur in constructor so that the instance of the object can not be created, should we throw the exception to the invoker of the constructor or simply catch the exception (and not throw it again)?

I think we should not catch the exception (and not throw it again), since in this approach, the invoker can not see whether the instance of the object has been created successfully.

I think we should throw the exception to let the invoker know that the instance of the object has not been created successfully, so that the invoker can peform appropriate actions. But I am not quite sure whether I am correct since I have not seen any constructors which throw exceptions before.

Could anyone help?


Thanks in advance,
George

You have to be careful when throwing exceptions in a constructor, that is if you want clean running code. Constructors should also return valid objects but sometimes can't due to errors. I guess the best way to deal with something of this senario is present clear error messages that let the user know what they failed to give or present, and second is to use the finally clause. The finally clause will give about the only way to "clean up" your code after failure, although you must be careful here also. Using the finally clause means that it will execute every time the code is run(you know this already), which means some kind of flag must be created in order for proper cleanup.

Hope that makes a little sense and helps out some. I'm sure you know all of that already and are seeking more advanced techniques, but that's about the only path you can go down on.

Thanks server_crash,

You have to be careful when throwing exceptions in a constructor, that is if you want clean running code. Constructors should also return valid objects but sometimes can't due to errors. I guess the best way to deal with something of this senario is present clear error messages that let the user know what they failed to give or present, and second is to use the finally clause. The finally clause will give about the only way to "clean up" your code after failure, although you must be careful here also. Using the finally clause means that it will execute every time the code is run(you know this already), which means some kind of flag must be created in order for proper cleanup.

Hope that makes a little sense and helps out some. I'm sure you know all of that already and are seeking more advanced techniques, but that's about the only path you can go down on.

Your reply is very helpful! You are always very warm-heated.


regards,
George

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.