Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Exception is not instance of Throwable?

Tags:

oop

php

php-5.6

I think in all programming languages Exception class is instance of Throwable interface.

Take a look at following code which shows Exception is not instance of Throwable in php.

try {

    throw new InvalidArgumentException("error message");

} catch (InvalidArgumentException $e) {

    if ($e instanceof Exception) {
        echo '$e is exception';             // this line gets executed
    }

    if ($e instanceof Throwable) {
        echo '$e is throwable';             // but this one never
    }

}

It makes problem with chaining exceptions where Exception class constructor accepts Throwable in it's last argument.

php version: 5.6.23

Any solution?

like image 868
Lost Koder Avatar asked May 02 '17 16:05

Lost Koder


People also ask

Can we cast throwable to Exception?

Throwable is a class which Exception – and consequently all subclasses thereof – subclasses. There's nothing stopping you from using instanceof on a Throwable .

What is difference between throwable and Exception?

The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses - Exception and Error. The Exception class is used for exception conditions that the application may need to handle.

How do you use throwable Exception?

Syntax: throw Instance Example: throw new ArithmeticException("/ by zero"); But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class.

Why do We use throwable in Java?

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.


1 Answers

Throwable is the base interface for any object that can be thrown via a throw statement in PHP 7, including Error and Exception. And your code produces: $e is exception $e is throwable if you have PHP version >= 7

But you have PHP version 5.6.23, so Throwable interface is not available for this version.

like image 70
arbogastes Avatar answered Oct 26 '22 14:10

arbogastes