tags:

views:

65

answers:

6

is there something similar in php to the try... else in python?

I need to know if the try block executed correctly as when the block executed correctly, a message will be printed.

+4  A: 

You can use try { } catch () { } and throw. See http://php.net/manual/en/language.exceptions.php

try {
    $a = 13/0; // should throw exception
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

or manually:

try {
    throw new Exception("I don't want to be tried!");
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
MvanGeest
Care to explain the downvote? Did I make a mistake?
MvanGeest
I didn't downvote, but he was asking about the `else` block, not exceptions in general...
ircmaxell
Oh, and `$a = 13/0;` will not throw an exception unless you have an error handler installed that throws exceptions (`set_error_handler(function($errno, $errstr, $errfile, $errline) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline);});`... http://www.php.net/manual/en/class.errorexception.php)
ircmaxell
Is PHP's "catch" block not equivalent to Python's "else" block?
enobrev
@enobrev: No it isn't. See my answer below.
webbiedave
It's not. Python uses `except:` as php's `catch` block. The `else` block is executed ONLY if no exceptions were thrown (the try-bock completed cleanly). `try: ... except: ... else: ...` http://docs.python.org/tutorial/errors.html#exceptions
ircmaxell
Ah, I see. Thanks for the clarification! Besides your response below, I figure one could put what would be inside the `else` block inside the `try` block, although I'm guessing the point here is to test those statements separately.
enobrev
@enobrev, the difference is that exceptions thrown in the `else` clause are not caught by the except/catch block. So a little more logic is required than just placing the else within the try (as my answer tries to communicate)...
ircmaxell
Ok, now I completely follow. Thanks!
enobrev
A: 

Not familiar with python but it sounds like you're after Try Catch blocks used with exceptions...

http://php.net/manual/en/language.exceptions.php

Cags
A: 

There is try-catch in php.

Example:

function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
Sarfraz
A: 

PHP does not have try/catch/else. You could however set a variable in the catch block that can be used to determine if it was run:

$caught = false;

try {
    // something
} catch (Exception $e) {
    $caught = true;
}

if (!$caught) {

}
webbiedave
This gets full of `$caught = true;` statements if there are several `catch` blocks.
Artefacto
But that's how the python `else` works as well.
webbiedave
One minor note, python's else block would only be executed if `$caught` is false, not true...
ircmaxell
Thanks ircmaxell. Edited.
webbiedave
A: 
try {
    $clean = false;
    ...
    $clean = true;
} catch (...) { ... }

if (!$clean) {
    //...
}

That's the best you can do.

Artefacto
You should set $clean to it's initial value before you enter the try..catch block. See webbiedave's answer.
jmz
@jmz Hum? Why? it's indifferent; there's no block scope in PHP.
Artefacto
A: 

I think the "else" clause is a bit limiting, unless you don't care about any exceptions thrown there (or you want to bubble those exceptions)... From my understanding of Python, it's basically the equivalent of this:

try {
    //...Do Some Stuff Here
    try {
        // Else block code here
    } catch (Exception $e) {
        $e->elseBlock = true;
        throw $e;
    }
} catch (Exception $e) {
    if (isset($e->elseBlock) && $e->elseBlock) {
        throw $e;
    }
    // catch block code here
}

So it's a bit more verbose (since you need to re-throw the exceptions), but it also bubbles up the stack the same as the else clause...

Edit Or, a bit cleaner version (5.3 only)

class ElseException extends Exception();

try {
    //...Do Some Stuff Here
    try {
        // Else block code here
    } catch (Exception $e) {
        throw new ElseException('Else Clasuse Exception', 0, $e);
    }
} catch (ElseException $e) {
    throw $e->getPrevious();
} catch (Exception $e) {
    // catch block code here
}

Edit 2

Re-reading your question, I think you may be overcomplicating things with an "else" block... If you're just printing (which isn't likely to throw an exception), you don't really need an else block:

try {
    // Do Some stuff
    print "Success";
} catch (Exception $e) {
    //Handle error here
    print "Error";
}

That code will only ever print either Success or Error... Never both (since if the print function throws the exception, it won't be actually printed... But I don't think the print CAN throw exceptions...).

ircmaxell