Page 1 of 1
try / catch assistance
Posted: Sun Jul 11, 2010 12:40 am
by hag
Why does the following code not work?
Code: Select all
<?php
try {
include "anypage.php";
} catch(Exception $e) {
echo 'Caught it';
}
?>
Hag
Re: try / catch assistance
Posted: Sun Jul 11, 2010 12:47 am
by requinix
General Posting Guidelines
Ask yourself - you're the only one who knows what "not work" means.
Unless you feel like sharing that information...
Re: try / catch assistance
Posted: Sun Jul 11, 2010 12:50 am
by hag
it doesn't work because i need a break... this works
Code: Select all
<?php
try {
if(!(@include 'anypage.php'))
{
throw new Exception();
}
} catch(Exception $e) {
echo 'Caught it!';
}
?>
Now time for chocolate milk....
Hag
Re: try / catch assistance
Posted: Sun Jul 11, 2010 12:52 am
by hag
I guess i meant why doesn't the catch block properly catch my try statement... i'm befuddled but now back on track... thanks for your assistance
Hag
Re: try / catch assistance
Posted: Sun Jul 11, 2010 2:54 am
by requinix
include() will only issue a warning if the file couldn't be included. Warnings/errors and exceptions are two totally different things.
So if you want an exception you have to throw one yourself. Pretty much like you're doing now.
Re: try / catch assistance
Posted: Mon Jul 12, 2010 3:21 pm
by hag
gotcha... what about require()... shouldn't it throw an exception?
Are there any built in PHP functions that will "include" a class file and throw and exception if it fails?
noob->Hag
Re: try / catch assistance
Posted: Mon Jul 12, 2010 5:56 pm
by Weirdan
hag wrote:gotcha... what about require()... shouldn't it throw an exception?
Are there any built in PHP functions that will "include" a class file and throw and exception if it fails?
Nope. You could convert warnings/notices to exceptions though, using set_error_handler() :
Code: Select all
class InternalErrorException extends Exception {
private $errorFile = null;
private $errorLine = null;
public function __construct($code, $message, $file, $line) {
parent::__construct($message, $code);
if ($file) {
$this->errorFile = $file;
}
if ($line) {
$this->errorLine = $line;
}
}
public function __toString() {
return "[{$this->getCode()}] {$this->getMessage()} ({$this->getErrorFile()}:{$this->getErrorLine()}) in \n{$this->getTraceAsString()}";
}
public function getErrorFile() {
return is_null($this->errorFile) ? '[unknown]' : $this->errorFile;
}
public function getErrorLine() {
return is_null($this->errorLine) ? '[unknown]' : $this->errorLine;
}
}
set_error_hander(function($errno, $errstr, $errfile, $errline, $errcontext) {
if (error_reporting() & $errno) {
throw new InternalErrorException($errno, $errstr, $errfile, $errline);
}
}, E_ALL);
Re: try / catch assistance
Posted: Tue Jul 13, 2010 11:40 pm
by hag
very nice.. thanks
Hag