AiD
AiD

Reputation: 1007

How to exit function from catch block in PHP

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

Answers (2)

Jerodev
Jerodev

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

Andreas
Andreas

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

Related Questions