SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
-
Jul 11, 2009, 08:36 #1
Is this proper use of exceptions?
PHP Code://in class
if(!require 'file.php'){
throw new Exception("file.php is needed");
}
Does that above statement work? It's located in a class object. Does it include file.php in the if statement?
PHP Code:try{
myvar = new Thing();
}
catch(Exception $e){
echo($e-> getMessage());
exit()
}
-
Jul 11, 2009, 09:08 #2
- Join Date
- Jul 2008
- Posts
- 5,757
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Yes, it's proper exception use. But the code won't work. If require fails, a fatal error occurs immediately. You could use include.
But, beware of the return value of include/require. If the file has a return statement in the files global scope, that will be used as the return value. See the documentation for include for more info.
Also be aware that if the code inside that file throws an exception, you will print an error message saying file is needed, even though the file was included. You could use a more specific type of exception if you want to distinguish.
-
Jul 11, 2009, 10:24 #3
- Join Date
- Mar 2008
- Posts
- 1,149
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
If the code inside the file throws an exception, it won't say that file.php is needed, because the exception is thrown before it gets to the 'throw new Exception("file.php is needed");' line.
-
Jul 11, 2009, 10:44 #4
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block.
If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler()
test:
PHP Code:<?php
class Thing
{
public function __construct()
{
$this->foo();
if (! require 'file1.php')
{
throw new Exception("file.php is needed");
}
$this->bar();
}
public function foo()
{
echo "bla";
}
public function bar()
{
echo "blar";
}
}
try
{
$myvar = new Thing();
}
catch (Exception $e)
{
$e->getMessage();
}my mobile portal
ghiris.ro
-
Jul 11, 2009, 11:11 #5
- Join Date
- Jul 2008
- Posts
- 5,757
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Bookmarks