0

till now I have never done anything dealing with exceptions.
Now I have to deal with exception. Basically I have function below which I want to wrap in try/exception. I want to connect to database and if database connection failed then it should catch exception that will do some stuffs and then return false.
If successful it just returns true.

Can one explain with grain of salt how exceptions are done in PHP. I have tried a lot to read but I get lost. I have only experience with Python exceptions that are a lot easier than in PHP

here is a function in question

public function __construct() {
        $conn = mysql_connect($this->dbuser, $this->dbpass , $this->dbhost) or die("Cannot connect to database: Error - ".mysql_error());
        mysql_select_db($this->dbname);
        return $conn;
    }
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Stefano Mtangoo
0

here's my take on them.


Once an exception is thrown, the rest of the code in the try will not be executed. It will then go to your catch (you can have more than 1 catch and define difference types, but is rarely done)

PHP will take the fatal error message and pass it to the catch

public function __construct() {
	try {

        	$conn = mysql_connect($this->dbuser, $this->dbpass , $this->dbhost) or die("Cannot connect to database: Error - ".mysql_error());
        	mysql_select_db($this->dbname);
        	return $conn;
    	}
	catch (Exception $e) {
    		echo 'Caught exception: ',  $e->getMessage(), "\n";
		return false;
	}

}
0

Thanks alot. I know the "general" work of try/exception. But I lack a lot for PHP. Thanks for your clear explanation. So can you explain a little more about how for example to do throw. For example in python I would do

try:
    #some code
except IOError:
    #do Some Code

Where do you specify something Like IOError? Or there is nothing like that in PHP?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.