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
Yes, It does.
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.
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:
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";
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With