Luuk Wuijster Luuk Wuijster - 1 year ago 69
PHP Question

why is try catch not working? What am I doing wrong? (php)

function TriggerContent($c, $db){

try {

include 'pages/' . $c . '.php';

$content= getContent();

} catch (Exception $e){

$content = 'Error';


return $content;


What I want it do is display the 'error' if the php file doesn't exists.
But it doesnt work... What am I doing wrong? Or will this just not work with try catch in php?

Answer Source

It's not working because a failed include doesn't throw an exception, it throws a warning. Therefor the catch block will never be executed, as you'll only enter it if there is an exception. You can just check if the file exists, and if it doesn't, throw an exception.

try {
    $page = 'pages/' . $c . '.php';

    if (!file_exists($page))
        throw new Exception('File does not exist: ['.$page.']');

    include $page;
    $content = getContent();

} catch (Exception $e){
    $content = 'Error: '.$e->getMessage();

If the targeted file doesn't exist, it will output

Error: File does not exist: [path-to-file]

in your $content variable.