Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP try-catch supports short notation?

Is this legal? Not near my work computer so can't test

try
    someClass::someStaticFunction();
catch(Exception $e)
    $e->getMessage();

Specifically the lack of brackets, similar to an if-else statement

if(someBool)
    someClass::someStaticFunction();
else
    someClass::someOtherFunction(); 

Cheers!

like image 498
PandemoniumSyndicate Avatar asked Jan 09 '12 22:01

PandemoniumSyndicate


People also ask

Can we use try catch in PHP?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

Can PHP try have multiple catches?

PHP allows a series of catch blocks following a try block to handle different exception cases. Various catch blocks may be employed to handle predefined exceptions and errors as well as user defined exceptions.

What is the syntax of try catch?

catch” syntax. It works like this: First, the code in try {...} is executed. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch .

What can I use instead of try catch?

If you've one if/else block instead of one try/catch block, and if an exceptions throws in the try/catch block, then the if/else block is faster (if/else block: around 0.0012 milliseconds, try/catch block: around 0.6664 milliseconds). If no exception is thrown with a try/catch block, then a try/catch block is faster.


2 Answers

No you must use the brace brackets. Note that you can catch exceptions by type :

try {
  someClass::someStaticFunction();
} catch (MyException $e) {
  // do specific stuff for this exception
} catch (Exception $e) {
  // do stuff for other exceptions
}
like image 171
fbableus Avatar answered Sep 30 '22 14:09

fbableus


No, doesn't seem like it works.

Check my example here: http://codepad.org/BpSBiPDY

like image 35
Jason Avatar answered Sep 30 '22 13:09

Jason