Cholthi Paul Ttiopic
Cholthi Paul Ttiopic

Reputation: 936

PHP, How are exceptions different from regular classes

Curiously, I made a Class with the same interface like base Exception Class but not extending/ derived from it. Just old plain PHP object to act like an exception. I knew this would not work as explained here but tried anyway since after all exceptions are just like normal classes.

class MyException {

/**
* properties omitted
*/

 public function __construct( string $message = "",int $code)

 public function getMessage(void)

 //more methods
} 

// somewhere in code block

  throw new MyException("Fatal error");
  // Fatal error: exceptions must be valid objects derived from exception base class.

Can you please explain other ways exceptions are different from regular classes and how they achieve their roles of being exceptional in our code. I know this might be stupid question, but I was just hoping to understand more about how exceptions really work.

Upvotes: 2

Views: 402

Answers (2)

axiac
axiac

Reputation: 72226

The Exception class is just container the programmer uses to pass information about the exception (an error code, a message, the location, the stack trace, other information that might be useful to handle the exception) from one part of the program (where the exception happened) to other part of the program (where there is code that knows how to handle it).

Its constructor does nothing more than storing the values it receives as arguments. The other methods are just getters; they are used to extract the values from the Exception object. The Exception class doesn't implement any behaviour.

Apart from the requirement to extend Exception, there is nothing special about it.

Upvotes: 1

JerzySBG
JerzySBG

Reputation: 109

Exception is normal class. It has to extend 'Exception', because PHP doesn't want to check if it has all required methods/properties (used by default PHP exception handler).

By extending class (or implementing interface) you prove that your class has methods like 'getMessage()' and it won't throw error about not existing method.

It must implement all Throwable interface methods (http://php.net/manual/en/class.throwable.php):

Throwable {
    /* Methods */
    abstract public string getMessage ( void )
    abstract public int getCode ( void )
    abstract public string getFile ( void )
    abstract public int getLine ( void )
    abstract public array getTrace ( void )
    abstract public string getTraceAsString ( void )
    abstract public Throwable getPrevious ( void )
    abstract public string __toString ( void )
}

Upvotes: 2

Related Questions