Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try Catch cannot work with require_once in PHP?

Tags:

php

I can't do something like this ?

try {     require_once( '/includes/functions.php' );       } catch(Exception $e) {         echo "Message : " . $e->getMessage();     echo "Code : " . $e->getCode(); } 

No error is echoed, server returns 500.

like image 485
user310291 Avatar asked Mar 20 '11 15:03

user310291


People also ask

Is there a try catch in PHP?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

What is the difference between include_once and require_once in PHP?

include_once will throw a warning, but will not stop PHP from executing the rest of the script. require_once will throw an error and will stop PHP from executing the rest of the script.

What does the require_once () function allow you to do?

The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.

What is the main difference between require () and require_once () in PHP?

The basic difference between require and require_once is require_once will check whether the file is already included or not if it is already included then it won't include the file whereas the require function will include the file irrespective of whether file is already included or not.


1 Answers

You can do it with include_once or file_exists:

try {     if (! @include_once( '/includes/functions.php' )) // @ - to suppress warnings,      // you can also use error_reporting function for the same purpose which may be a better option         throw new Exception ('functions.php does not exist');     // or      if (!file_exists('/includes/functions.php' ))         throw new Exception ('functions.php does not exist');     else         require_once('/includes/functions.php' );  } catch(Exception $e) {         echo "Message : " . $e->getMessage();     echo "Code : " . $e->getCode(); } 
like image 162
a1ex07 Avatar answered Oct 17 '22 03:10

a1ex07