Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the PHP equivalent to Python's Try: ... Except:

I am a strong Python programmer, but not quite there when it comes to PHP. I need to try something, and if that doesn't work out, do something else.


This is what it would look like in Python:

try:
      print "stuf"
except:
      print "something else"

What would this be in PHP?

like image 373
Zac Brown Avatar asked Oct 18 '10 02:10

Zac Brown


People also ask

What can I use instead of try and except in Python?

If the situation satisfies the above conditions, you don't have to use try ... except ... to handle the exceptions. Instead, the Python built-in library contextlib provides a function called suppress to handle this more elegantly.

Can we use try without catch in PHP?

Try, throw and catch Proper exception code should include: try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal.

What is Python try except?

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.

Is try except the same as if else?

The if-else block works preemptively and stops the error from occurring while the try-except block handles the error after it has occurred. So, In try-except block system usage is more than if-else block.


1 Answers

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

try {
    print 'stuff';
} catch (Exception $e) {
    var_dump($e);
}

Note: this only works for exceptions, not errors.

See http://www.php.net/manual/en/function.set-error-handler.php for that.

like image 137
Petah Avatar answered Oct 06 '22 01:10

Petah