4

I am trying to understand what the best approach would be to handle Exceptions in the following scenario:

I have a class employee:

class employee extends person {
    private $salary;
    private $baseSalary = 6.5;

    function __construct($f, $m, $l, $a,$fsalary=0){
        if(!is_numeric($fsalary)){
            throw new Exception("Age supplied is not a number", 114);
        }
        parent::__construct($f, $m, $l, $a);    
        $this->salary=$fsalary;
    }
    function GetDetails(){
         return parent::GetName().
                "<br/>".
                $this->salary;
    }
    function __toString(){
        return $this->GetDetails();
    }

}

And using this:

try{
    if(!$f = new employee("Sarah", "Sebastian", "Pira", "abc")){
        throw new Exception();
    }
    else {
        echo $f;        
    }

}
catch (Exception $e){
    echo "<br/>";
    echo var_dump($e);
}

Now I would think it would be a good idea to throw an exception in the class and then use just one catch block in all the scripts that would be using an employee object - But this doesn't seem to work - I need to have a try catch block within the class - Is this the correct way of looking at this?

Thanks

5
  • Which part doesn't work? What are you expecting to happen in the second code block? It reads like no Exceptions will be thrown, and it will just echo Sarah Sebastian Pira <br/> 0 right? Commented May 6, 2011 at 23:54
  • If the employee object is used in a separate script the catch block of the class isn't fired when the object is created - My question is that is it possible to have one try catch block defined in the class rather than having a try catch block on every instance where the employee object is used? Commented May 7, 2011 at 5:16
  • When using this approach I get a fatal error stating that the exception was uncaught Commented May 7, 2011 at 6:03
  • 1
    Just FYI: It's a very unusual coding style to use class names beginning with a lowercase character and method names starting with a uppercase character in PHP. Normally, it would be class Employee extends Person and function getDetails. Commented May 7, 2011 at 9:31
  • Another tips: 1) do not throw empty exceptions! 2) do not use assignments within the condition (unless you really know what you are doing - and understand how it works) Commented May 9, 2011 at 23:59

2 Answers 2

4

I think what you're saying is that you want to do something like this:

try {
    class Employee extends Person {
        // ...blah blah...
    }
}
catch(Exception $e) {
    // handle exception
}

...and then be able to insantiate it in other classes, without explicitly catching any exceptions:

// try { << this would be removed
    $employee = new Employee();
// }
// catch(Exception $e) {
//    (a whole bunch of code to handle the exception here)
// }

You can't do that, because then the try/catch block in the class will only catch any exceptions that occur when defining the class. They won't be caught when you try to instantiate it because your new Employee line is outside the try/catch block.

So really, your problem is that you want to be able to re-use a try/catch block in multiple places without re-writing the code. In that case, your best solution is to move the contents of the catch block out to a separate function that you can call as necessary. Define the function in the Employee class file and call it like this:

try {
     $employee = new Employee();
     $employee->doSomeStuff();
     $employee->doMoreStuffThatCouldThrowExceptions();
}
catch(Exception $e) {
    handle_employee_exception($e);
}

It doesn't get rid of the try/catch block in every file, but it does mean that you don't have to duplicate the implementation of the exception-handling all the time. And don't define handle_employee_exception as an instance method of the class, do it as a separate function, otherwise it will cause a fatal error if the exception is thrown in the constructor because the variable won't exist.

Sign up to request clarification or add additional context in comments.

Comments

4

You should read more about Exceptions in PHP.

You can handle exceptions within the methods of the class, sure. But you should rethink how you want to do this and... why.

Good practice is also creating own exception class, so you are able to distinguish exceptions thrown by your module / class from the exceptions thrown by something else. It looks like that (see more):

class EmployeeModule_Exception extends Exception {}

and when it comes to throwing exception:

// the second parameter below is error code
throw new EmployeeModule_Exception('some message', 123);

Catching is similar, only the below example will catch only your module's exceptions:

try {
    // some code here
} catch (EmployeeModule_Exception $e) {
    // display information about exception caught
    echo 'Error message: ' . $e->getMessage() . '<br />';
    echo 'Error code: ' . $e->getCode();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.