i am trying to understand the use of exceptions in PHP.. How they work and when to use them… The basic structure below, is the the correct method.. It seems somewhat bloated to me?
Thanks in advance for any advise or help..
<?php
class APIException extends Exception
{
public function __construct($message)
{
parent::__construct($message, 0);
}
public function __toString()
{
echo('Error: ' . parent::getMessage());
}
public function __toDeath()
{
die("Oops: ". parent::getMessage());
}
}
?>
<?php
require_once('exception.class.php');
class auth extends base
{
/*
* User functions
*/
public function user_create($args='')
{
try
{
if ( !isset($arg['username']) || !isset($arg['password']) ||
!isset($arg['question']) || !isset($arg['answer']) )
{
throw new APIException('missing variables, try again');
}
}
catch (APIException $e)
{
$e->__toString();
}
try
{
if ( $this->user_exists() )
{
throw new APIException('user already exists');
}
}
catch (APIException $e)
{
$e->__toString();
}
}
protected function user_exists($name)
{
// Do SQL Query
try
{
$sql = "select * from user where username='$user'";
if (!mysql_query($sql))
{
throw new APIException('SQL ERROR');
}
}
catch (APIException $e)
{
$e->__toDeath();
}
}
}
?>
No, you’re not using them correctly. Take a look at this
When you
throw new APIException('missing variables, try again');, it will just be caught bycatch (APIException $e).One of the points of exceptions is so that you can tell code calling the function that something went wrong. A more proper usage might look something like this.
Notice that the you use the try/catch block when you call user_create. Not within user_create.