$ e in php exceptions

I am new to PHP and browsing php.net where I came across this piece of code:

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo "Hello World\n";
?>

      

What is it $e

? Can you rename? What does it do? Why do we need this?

+3


source to share


3 answers


It's just a variable, you can call it whatever you want. Basically variable points to an Exception object, and it is conventionally called $ e as the "e" for brevity E .

Also, when using exceptions, it is a good idea to create your own exception classes by simply creating a new class that extends Exception. For example:

<?php

class AuthException extends Exception {}

class SuspendedException extends Exception {}

      

In this case, you may throw new AuthException()

not be able to authenticate the user. On the other hand, if the user manages to log in but is blocked from your page, you can throw new SuspendedException()

.



This way you can extend your try-catch blocks to catch different exceptions and handle them differently.

<?php

try {
    //logging your user in
} catch (AuthException $ae) {
    //handle an unauthorized user
} catch (SuspendedException $se) {
    //handle a suspended user
}

      

Please note that I am using $ae

and $se

and not simple $e

- as I said earlier, these are only variables and can be named whatever you like. Just try to stay consistent with your code.

+2


source


$e

is the variable that contains the object Exception

, so yes, you can rename it. What it does is that if there is some kind of exception in your try block, then the catch block is triggered, so you might get the exception, perhaps log it, try something else, or print a useful error to the user.



http://php.net/manual/en/language.exceptions.php

+2


source


It can be renamed to any legal PHP variable name and has a message and associated information about the exception that occurred. Use var_dump()

to view information.

0


source







All Articles