Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SarahS's avatar
Level 12

PHP Exceptions

I'm following the course PHP Practitioner and I'm having some problems with displaying Exceptions. My code is this:

    public function direct($uri, $requestType)
    {
        if (array_key_exists($uri, $this->routes[$requestType])) {
            return $this->callAction(
                ...explode('@', $this->routes[$requestType][$uri])
            );
        }

        throw new Exception('No route defined for this URI.');
    }

But when I run it and try a route that I know won't work I get a Fatal Error instead. It says:

Fatal error: Uncaught Error: Class 'App\Core\Exception' not found in ...

Now I haven't declared Exception or anything, do I need to add anything like that to use it? Thanks

0 likes
5 replies
MichalOravec's avatar

Add this to the top of your file.

use Exception;

Because if your file is in a namespace you will need to add it.

martinbean's avatar

@sarahs74 Yeah, you’ll need to import the Exception class at the top of your file:

use Exception;

You can then throw instances of Exception in your code as you were trying to do :)

SarahS's avatar
Level 12

Thanks, I've added that but now instead of the written exception I get:

Fatal error: Uncaught Exception: No route defined for this URI. 

I though it should just output what I have in the quotes?

martinbean's avatar

@sarahs74 That’s the exception being thrown. So if the if statement above doesn’t eventually to being true, your code will carry on to the exception underneath. So you’ll see that the message (No route defined for this URI.) is the same as what is in the exception code.

So where ever you call your direct method, you’ll need to “catch” the exception if you want to handle it instead of the exception halting your program:

try {
    $someClass->direct($uri, $requestType);
} catch (Exception $e) {
    // If an exception is thrown above in the “try” block,
    // you will end up here.

    // Do something with the exception here if you need to.
    // $e->getMessage() = "No route defined for this URI."
}

Please or to participate in this conversation.