Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$e in php exceptions

Tags:

exception

php

I'm new to PHP and was 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 exactly is $e? Can it be renamed? What does it do? Why do we need it?

like image 967
ufosecret Avatar asked May 02 '26 19:05

ufosecret


1 Answers

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

Also, when using Exceptions, it's a good idea to create your own Exception-classes by just creating a new class that extends Exception. For example:

<?php

class AuthException extends Exception {}

class SuspendedException extends Exception {}

In this case, you can throw new AuthException() should a user fail to authenticate. On the other hand, if a user manages to login but is suspended 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
}

Notice how I'm using $ae and $se rather than a plain $e - as I said earlier, those are only variables and can be named whatever you like. Just try to stay consistent with your code.