Reputation: 1007
I try to get value from an external API, in failure i catch an exception, but i want to go out of my main function, can i do that into catch ?
public function test()
{
....
$val = this->getVal($id)
this->getx($val);
this->gety($val);
}
private function getVal($id)
{
try {
//trying to get value from an other API
} catch (\Exception $e) {
// here i want to go out from test function ..
}
return $value;
}
Upvotes: 0
Views: 725
Reputation: 33186
The cleanest solution, in my opinion, is to throw a specific exception and catch that where your test function is called. This way execution is stopped and resumed in the catch block.
try {
test();
} catch (MyCustomException $e) {
// Test has been halted
}
public function test()
{
....
$val = this->getVal($id)
this->getx($val);
this->gety($val);
}
private function getVal($id)
{
try {
//trying to get value from an other API
} catch (\Exception $e) {
throw new MyCustomException;
}
return $value;
}
Upvotes: 3
Reputation: 23958
The most obvious I can think of is to return something that exits the rest of test().
Example:
public function test()
{
....
$val = this->getVal($id)
if($val !== false){
this->getx($val);
this->gety($val);
}
}
private function getVal($id)
{
try {
//trying to get value from an other API
} catch (\Exception $e) {
// here i want to go out from test function ..
$value = false; // or null, or what suits the rest of the code
}
return $value;
}
Upvotes: 1