Php exception class name

PHP check thrown exception type

You can have multiple catch blocks to catch different Exception types. See below:

try < /* code with exceptions */ >catch (MyFirstCustomException $e) < // We know it is a MyFirstCustomException >catch (MySecondCustomException $e) < // We know it is a MySecondCustomException >catch (Exception $e) < // If it is neither of the above, we can catch all remaining exceptions. >

You should know that once an Exception is caught by a catch statement, none of the following catch statements will be triggered, even if they match the Exception.

You can also use the get_class method to get the full class name of any object, including Exceptions.

This in my opinion is the correct answer. to test the class type means you probably know what class type you are looking for is and therefore can create the appropriate catch statements.

I think using instanceof is a better solution, since it gives you more information than just class name which you get from get_class .

class db_exception extends Exception <> class db_handled_exception extends db_exception <> class db_message_exception extends db_exception <> function exception_type($ex)< echo '
'; echo 'Type: [' . get_class($ex) . "]\n"; echo "Instance of db_message_exception? " . var_export($ex instanceof db_message_exception,true) . "\n"; echo "Instance of db_handled_exception? " . var_export($ex instanceof db_handled_exception,true) . "\n"; echo "Instance of db_exception? " . var_export($ex instanceof db_exception,true) . "\n"; echo "Instance of Exception? " . var_export($ex instanceof Exception,true) . "\n"; echo '

'; > exception_type(new db_handled_exception()); exception_type(new db_message_exception()); exception_type(new db_exception()); exception_type(new exception());

Which will result as following

Type: [db_handled_exception] Instance of db_message_exception? false Instance of db_handled_exception? true Instance of db_exception? true Instance of Exception? true Type: [db_message_exception] Instance of db_message_exception? true Instance of db_handled_exception? false Instance of db_exception? true Instance of Exception? true Type: [db_exception] Instance of db_message_exception? false Instance of db_handled_exception? false Instance of db_exception? true Instance of Exception? true Type: [Exception] Instance of db_message_exception? false Instance of db_handled_exception? false Instance of db_exception? false Instance of Exception? true 

There might be cases that you want to categorize exceptions and do common actions.

Considering above example, you might want to only show exceptions that are of type db_message_exception and db_handled_exception ; in this case since both of them are inherited from db_exception, you can simply say something like:

if ($ex instanceof db_exception) < // show error message >

You might also want to wrap your exceptions to avoid spilling too much information to client screen:

if (!($ex instanceof db_exception))

Источник

Exception

Exception is the base class for all user exceptions.

Class synopsis

Properties

The filename where the exception was created

The line where the exception was created

The previously thrown exception

The string representation of the stack trace

The stack trace as an array

Table of Contents

  • Exception::__construct — Construct the exception
  • Exception::getMessage — Gets the Exception message
  • Exception::getPrevious — Returns previous Throwable
  • Exception::getCode — Gets the Exception code
  • Exception::getFile — Gets the file in which the exception was created
  • Exception::getLine — Gets the line in which the exception was created
  • Exception::getTrace — Gets the stack trace
  • Exception::getTraceAsString — Gets the stack trace as a string
  • Exception::__toString — String representation of the exception
  • Exception::__clone — Clone the exception

User Contributed Notes 3 notes

Lists of Throwable and Exception tree as of 7.2.0

Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
ArgumentCountError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException
SodiumException

Note that an exception’s properties are populated when the exception is *created*, not when it is thrown. Throwing the exception does not seem to modify them.

Among other things, this means:

* The exception will blame the line that created it, not the line that threw it.

* Unlike in some other languages, rethrowing an exception doesn’t muck up the trace.

* A thrown exception and an unthrown one look basically identical. On my machine, the only visible difference is that a thrown exception has an `xdebug_message` property while an unthrown one doesn’t. Of course, if you don’t have xdebug installed, you won’t even get that.

Note: this documentation not full, ReflectionObject::export($exception):
Object of class [ class Exception implements Throwable ] — Properties [ 7 ] Property [ protected $message ]
Property [ private $string ]
Property [ protected $code ]
Property [ protected $file ]
Property [ protected $line ]
Property [ private $trace ]
Property [ private $previous ]
>
— Methods [ 11 ] Method [ final private method __clone ] >

Method [ public method __construct ]

— Parameters [ 3 ] Parameter #0 [ $message ]
Parameter #1 [ $code ]
Parameter #2 [ $previous ]
>
>

Method [ public method __wakeup ] >

Method [ final public method getMessage ] >

Method [ final public method getCode ] >

Method [ final public method getFile ] >

Method [ final public method getLine ] >

Method [ final public method getTrace ] >

Method [ final public method getPrevious ] >

Method [ final public method getTraceAsString ] >

Method [ public method __toString ] >
>
>
?>

Missed:

Property [ private $string ]
Property [ private $trace ]
Property [ private $previous ]

Method [ public method __wakeup ] >

  • Predefined Exceptions
    • Exception
    • ErrorException
    • Error
    • ArgumentCountError
    • ArithmeticError
    • AssertionError
    • DivisionByZeroError
    • CompileError
    • ParseError
    • TypeError
    • ValueError
    • UnhandledMatchError
    • FiberError

    Источник

    What Exception subclasses are built into PHP?

    I have not yet been able to find a list of all the built-in Exception sub classes in PHP. I’d rather use built in ones when they make sense, before creating my own exception subclasses. For example, I know InvalidArgumentException exists, but there appears to be nothing comparable to Java’s NullPointerException. Does anyone have or can link to a list of the available Exception subclasses in PHP?

    PHP does not have NULL pointers. Trying to read an undefined variable is not an error and will result in merely a notice.

    Actually, if dealing with objects, PHP can issue a PHP Fatal error: Call to a member function on a non-object . That would probably be the closest thing to a NullPointerException. Your instantiation/client code should be verifying object creation/validity. Beyond that you can set set_error_handler

    @EmilVikström It may not be an error in PHP, but it is an error in the code logic which is the part of the reason to use exceptions.

    @webbiedave Specifically I’m writing code that others will call into. I can’t know that they’ll be using my code correctly, and it wouldn’t be my responsibility to correct the issue, merely to let them know they made a mistake. But the question is meant generally to get info about available exceptions.

    3 Answers 3

    PHP 5 has two built in exceptions

    Libraries within PHP have their own built in exceptions

    • DOMException DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.
    • IntlException his class is used for generating exceptions when errors occur inside intl functions. Such exceptions are only generated when intl.use_exceptions is enabled.
    • PharException Thrown when working with the Phar class
    • ReflectionException Thrown when working with Reflection classes
    • BadFunctionCallException A callback refers to an undefined function or if some arguments are missing.
    • BadMethodCallException A callback refers to an undefined method or if some arguments are missing.
    • DomainException A value does not adhere to a defined valid data domain.
    • InvalidArgumentException The arguments passed were invalid.
    • LengthException The parameter exceeds the allowed length (used for strings, arrays, file size, etc.).
    • LogicException Generic error occurred in program logic.
    • OutOfBoundsException An illegal index was requested.
    • OutOfRangeException An illegal index was requested. This represents errors that should be detected at compile time.
    • OverflowException Adding an element to a full container.
    • RangeException Indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow.
    • RuntimeException An error which can only be found on runtime occurs.
    • UnderflowException Performing an invalid operation on an empty container, such as removing an element.
    • UnexpectedValueException An unexpected value was received (i.e. as the result of a returned value from a method call).

    PHP 7 introduces new exceptions including catchable errors. New exceptions include:

    • Throwable is the base interface for any object that can be thrown via a throw statement in PHP 7, including Error and Exception.
    • Error is the base class for all internal PHP errors.
    • AssertionError is thrown when an assertion made via assert() fails.
    • ParseError is thrown when an error occurs while parsing PHP code, such as when eval() is called.
    • TypeError There are three scenarios where a TypeError may be thrown. The first is where the argument type being passed to a function does not match its corresponding declared parameter type. The second is where a value being returned from a function does not match the declared function return type. The third is where an invalid number of arguments are passed to a built-in PHP function (strict mode only).
    • ArithmeticError is thrown when an error occurs while performing mathematical operations. In PHP 7.0, these errors include attempting to perform a bitshift by a negative amount, and any call to intdiv() that would result in a value outside the possible bounds of an integer.
    • DivisionByZeroError is thrown when an attempt is made to divide a number by zero.
    • ArgumentCountError is thrown when too few arguments are passed to a user-defined function or method.

    PHP 7.3 introduces JSON exceptions:

    PHP 8 introduces one new exception:

    • ValueError is thrown when you pass a value to a function, which has a valid type but can not be used for the operation.

    Here’s a chart that demonstrates the new hierarchy introduced in PHP 7:

    \Throwable ├── \Exception (implements \Throwable) | |── \DOMException (extends \Exception) | ├── \IntlException (extends \Exception) | ├── \JsonException (extends \Exception) | |── \PharException (extends \Exception) | |── \ReflectionException (extends \Exception) | |── \ValueError (extends \Exception) │ ├── \LogicException (extends \Exception) │ │ ├── \BadFunctionCallException (extends \LogicException) │ │ │ └── \BadMethodCallException (extends \BadFunctionCallException) │ │ ├── \DomainException (extends \LogicException) │ │ ├── \InvalidArgumentException (extends \LogicException) │ │ ├── \LengthException (extends \LogicException) │ │ └── \OutOfRangeException (extends \LogicException) │ └── \RuntimeException (extends \Exception) │ ├── \OutOfBoundsException (extends \RuntimeException) │ ├── \OverflowException (extends \RuntimeException) │ ├── \RangeException (extends \RuntimeException) │ ├── \UnderflowException (extends \RuntimeException) │ └── \UnexpectedValueException (extends \RuntimeException) └── \Error (implements \Throwable) ├── \AssertionError (extends \Error) ├── \ParseError (extends \Error) └── \TypeError (extends \Error) └── \ArgumentCountError (extends \TypeError) └── \ArithmeticError (extends \Error) └── \DivisionByZeroError extends \ArithmeticError) 

    Источник

    Читайте также:  Untitled Document
Оцените статью