How come you don't need to name exception php?

When you throw an exception you don't name it, why is this? I read that is an object, don't you need to assign an object to a variable? e.g.

throw new Exception('Division by zero.');

And how does this work:

catch (Exception $e){
//do something

What does Exception $e mean, is this some kind of shorthand for declaring an object?


throw is just a keyword that you need to follow by an object of type Exception or another class based on the Exception class. The Exception class constructor takes a string argument which instantiates an Exception object with that exception message.

The catch block functions basically as a method that is called with the Exception object after the throw keyword. The catch block takes an Exception object as a parameter which in this case is named $e inside the catch block.

This is the Exception class construct:

public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )

Read more about the Exception class here

If you want you can even name the Exception object before throwing it:

try {
    $ex = new Exception('Test exception.');
    throw $ex;

} catch (Exception $e) {
    echo "Cacthed exception.";

Need Your Help

JQuery prevent links working whilst ajax is loading

javascript php jquery ajax disabled-control

I have a firework detonation system which uses JQuery to connect to a PHP script via AJAX to detonate the fireworks. The only problem is that if you click one launch button straight after another, ...

PHP - Populating Display Input Data with MySQL Data from Table

php mysql forms class function

I am trying to populate results with a description from my MySQL database table interest_type

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.