This might be a bit of a stupid question but it has been bugging me 开发者_如何学编程so here goes
I know that the normal advice is that Exceptions are only meant to be used in exceptional circumstances but I also read people advocating to use exceptions when a method fails to fulfil its contract
Cancellation seems to me sit in a bit of a grey area between these two cases
Without exceptions if your class has a lot of cancelable actions your code ends up back checking error codes all over the place
Can cancelling be considered exceptional in this context?
Exceptions are most efficient for rare conditions that need non-local handling. It sounds like that applies here. So it is purely a stylistic question. Non-local control transfer can be more difficult to think about, but it will probably also mean shorter code. I would base the decision based on what language this is and how much of the existing code is already designed with exceptions. If you have exception-safe cleanup code already, go ahead and use them.
I wouldn't use an "exception" in its literal definition. What you could opt for is capturing the cancellation as a user driven value, a Boolean perhaps, that indicates that a user canceled out of an action, and use this Boolean to not perform the exhaustive error condition checks.
it depends on the language you are using. in php for example its a common practice to throw an exception and catch it to interrupt for example a loop or recursion that is called within an object where its not sufficient to just jump up to the parent function. consider this example:
<?php
class hideAndSeekWithOnlyOneOtherPlayer {
public function seek() {
foreach($rooms as $room) {
if($this->checkRoom($room)) {
$this->shoutThatIFoundYou();
return;
}
}
$this->shoutThatICantFindYou();
}
function checkRoom($room) {
$hideouts = $this->getPossibleHideoutsForRoom($room);
return $this->checkHideouts($hideouts);
}
function checkHideouts($hideouts) {
foreach($hideouts as $hideout) {
return $this->checkHideout($hideout);
}
return false;
}
function checkHideout($hideout) {
$this->walkToHideout();
return $this->seeIfPersonIsInsideHideout();
}
}
?>
its annoying to always pass the boolean value from one function to another, instead you could just throw an excemption in seeIfPersonIsInsideHideout() and dont care for the return values at all! maby this is a bad example because it really gets important when you have multiple cases that can occour. then you have to bass back a constant or string or integer that you check for in an case statement etc. its much better (easier to code and undestand, less error potential) to define your own exception class then!
精彩评论