I think you say you want to do something like this:
try { class Employee extends Person {
... and then be able to impose it in other classes without explicitly throwing any exceptions:
// try { << this would be removed $employee = new Employee(); // } // catch(Exception $e) { // (a whole bunch of code to handle the exception here) // }
You cannot do this because then the try / catch block in the class will catch only the exceptions that occur when the class is defined. They will not be caught when trying to instantiate, because your new Employee line is outside the try / catch block.
So your problem is that you want to be able to reuse the try / catch block in several places without re-writing the code. In this case, the best solution is to move the contents of the catch block into a separate function, which you can call as needed. Define the function in the Employee class file and call it as follows:
try { $employee = new Employee(); $employee->doSomeStuff(); $employee->doMoreStuffThatCouldThrowExceptions(); } catch(Exception $e) { handle_employee_exception($e); }
It does not get rid of the try / catch block in every file, but that means you don't have to duplicate the exception handling implementation all the time. And do not define handle_employee_exception as a class instance method, do it as a separate function, otherwise it will lead to a fatal error if an exception is thrown in the constructor because the variable will not exist.
source share