tags:

views:

32

answers:

2

I just want to confirm my understanding of exceptions and how they impact their objects.

If I throw an exception, that halts the processing of a method, correct? So there's no point in doing

if ( some_check() ) {
    throw new Exception(...);
} else {
    ...
}

I should just do this

if ( some_check() ) {
    throw new Exception(...);
} 

rest_of_code();

Also, if I throw an exception in __construct, that destroys the object, right? So I should do all my argument validation exception-throwing right up front -- there's no point in building the object if it's gonna get blown up anyway in an input validation exception.

+1  A: 

Yep you got it right :D You have a vote up from me :D

Allthough consider this, you might have two tests on one data :D

if( checkOne (a)){
   throw new Exception(...);
}
else (checkTwo(a)){
...
Hassan Syed
Isn't the `else` redundant in the second check? Isn't `if(){} if(){}` more or less the same?
If checkOne checks if patient has hemangiomas on face, and checktwo checks if the hemangiomas has hairs growing out of it (a hypothetical sign of cancer) then it makes sense to nest the checks this way. checkTwo wouldn't execute for patients without hemangiomas.
Hassan Syed
That was quite a contrived example :D Some programming languages generate armies of nested statements like this :D Decision support systems are implemented in such programming languages.
Hassan Syed
Oh, I get it now. Thanks, Syed! That makes a lot of sense :) It's when the second check is dependent on the value of the first -- not directly related to throwing exceptions.
A: 

It's quite normal to throw an exception in a constructor, you are left with no other option. Also you did not mention objects that hold some sort of memory resource, make sure you are using a using statement or a try / catch / finally and release the memory with the exception.

JonH
Does php support `finally`?
Sorry thought this was C#.
JonH