Search code examples
phpexceptioninstance-variablesthrow

php exception handling setting message afterwards


we usually set the message at instantiation, like this:

throw new Exception($msg);`

but I am in a situation where I have a default exception object stored in an instance variable and use it through out the objects lifetime, something like this:

throw $this->my_exception;

Since I am reusing the same object, I need to be able to set message at any time before throwning the exception, you see?


Solution

  • Don't do that. It makes tracing the exception harder (since the stacktrace won't include the re-throw). Instead, if you're using 5.3+ use the $previous parameter and make a new exception:

    throw new Exception("message", 0, $this->my_exception);
    

    Even if you're using less than 5.3, you can extend the exception class and add it...

    Edit: Ok, based on your comments, I see what you're trying to do now. You want to make your class throw a configurable exception. What I would do, is take a string class name in and store that. So $this->my_exception would be a string. You should verify that it's an exception class before storing it since you can't throw something that doesn't extend from Exception:

    if (!is_subclass_of($this->my_exception, 'Exception')) {
        //Error out, since you can't throw that class name
    }
    

    Then, when it's time to throw:

    $class = $this->my_exception;
    throw new $class("MyMessage");
    

    It's still not great since exceptions are supposed to have semantic meaning (hence the existence of LogicException and InvalidArgumentException), but if it's a requirement, that's not a horrible way of doing it (but pre-instantiating an exception is a horrible way of doing it)...