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_ch开发者_如何学Pythoneck() ) {
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.
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)){
...
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.
精彩评论