Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break from try/catch block

Is this possible in PHP?

try {

  $obj = new Clas();

  if ($obj->foo) {
    // how to exit from this try block?
  }

  // do other stuff here

} catch(Exception $e) {

}

I know I can put the other stuff between {}, but that increases indenting on a bigger code block and I don't like it :P

like image 715
Elfy Avatar asked May 09 '13 19:05

Elfy


People also ask

Does Break work in try catch?

Yes, It does.

Does catch break loop?

No - the loop will be exited from the point when the exception is thrown - after catch block is done with. Show activity on this post.


3 Answers

With a goto of course!

try {

  $obj = new Clas();

  if ($obj->foo) {
    goto break_free_of_try;
  }

  // do other stuff here

} catch(Exception $e) {

}
break_free_of_try:
like image 62
Justin Watt Avatar answered Sep 19 '22 13:09

Justin Watt


Well, there is no reason for that, but you can have fun forcing an exception in your try block, stopping execution of your function.

try {
   if ($you_dont_like_something){
     throw new Exception();
     //No code will be executed after the exception has been thrown.
   }
} catch (Exception $e){
    echo "Something went wrong";
}
like image 35
sybear Avatar answered Sep 22 '22 13:09

sybear


I also faced this situation, and like you, didn't want countless if/else if/else if/else statements as it makes the code less readable.

I ended up extending the Exception class with my own. The example class below was for validation problems that when triggered would produce a less severe 'log notice'

class ValidationEx extends Exception
{
    public function __construct($message, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    public function __toString()
    {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }
}

In my main code I call it;

throw new ValidationEx('You maniac!');

Then at the end of the Try statement I have

        catch(ValidationEx $e) { echo $e->getMessage(); }
        catch(Exception $e){ echo $e->getMessage(); }

Happy for comments and criticisms, we're all here to learn!

like image 43
Dan Avatar answered Sep 22 '22 13:09

Dan