By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,444 Members | 3,110 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,444 IT Pros & Developers. It's quick & easy.

Exception : an ugly grammer in programming

P: n/a
Well, friend. Yes, I'm doing PHP. But exception is a traditional
machinism in programming languages. I'm very doubt about this.
In procedure language, we return error code when we meet an error. So
we need to design error code table and judge them in several
statements. Finally they become boring.
But how about use exception in OOP? Did we drop all "return error
code" styles?
If i want to fetch a webpage:

<?php
function fetchPage($url)
{
//...do something

//if the net speed is very slow, cause we can't fetch the page
throw new SlowNetSpeed("page can't be getted");

//if the page is moved
throw new NoPage("page does't exist");

//...do something
}

// so what can i do, if i want the fetchPage procedure go on fetching
when SlowNetSpeed Exception happen?
// it stop when NoPage Exception happen?
while (1)
{
try
{
$c = fetchPage('Some_Where');
// do something
break;
}
catch (SlowNetSpeed $e)
{
}
catch(NoPage $e)
{
break;
}
}
?>
It is very ugly if there exists more Exceptions and other procedure.

Then i'm missing "return error code" style. But i know "return error
code" is not a good method when we deal with error. And exception is
also an ugly grammer when we want to keep code clean.

Jul 17 '07 #1
Share this Question
Share on Google+
7 Replies


P: n/a
Well, friend. Yes, I'm doing PHP. But exception is a traditional
machinism in programming languages. I'm very doubt about this.
In procedure language, we return error code when we meet an error. So
we need to design error code table and judge them in several
statements. Finally they become boring.
But how about use exception in OOP? Did we drop all "return error
code" styles?
<snip>
// so what can i do, if i want the fetchPage procedure go on fetching
when SlowNetSpeed Exception happen?
I think you'll have to decide. Is it something that can be repaired from
outside the object? if so, you can throw an exception. Is it not broken
at all? Then it is not an exception. You could implement an event
mechanism (java style) to handle this events and just continue fetching.

The way I see it, it is the responsibility of the fetcher class to fetch
the page and inform the user if it can take a while. Not being able to
perform that task is an exception, but a slow connection is not.

So I would do something like:

class ConnectionNotifier
{public function NotifySlowConnection()
{echo 'Please have patience. It is rather busy at the moment.';}
}

class PageFetcher
{private $_slowConnectionWarner;
public function __construct(ConnectionNotifier $slowConnectionWarner)
{$this->_slowConnectionWarner = $slowConnectionWarner;}
public function FetchPage($URL)
{$connection = ... // establish a connection here
if(! $connection):
throw new NoPageException();
endif;
// if you notice a slow connection, withing a fetching loop:
$this->_slowConnectionWarner->NotifySlowConnection();
}
}

Off course, you would add code to make sure there is only one
notification, but you could do that in the ConnectionNotifier class to
keep the code clean.

Best regards,
--
Willem Bogaerts

Application smith
Kratz B.V.
http://www.kratz.nl/
Jul 17 '07 #2

P: n/a
Did you consider using custom error handler? You will be able to call
it with trigger_error function with custom error levels, plus you can
control where the error message goes (email, log, etc.) Here's an ugly
example:

<?php
// set the user error handler method to be hl_error_handler
set_error_handler("hls_error_handler", E_ALL);
// error handler function
function hls_error_handler($errNo, $errStr, $errFile, $errLine)
{
/* the first two elements of the backtrace array are irrelevant:
-DBG_Backtrace
-outErrorHandler */
$backtrace = dbg_get_backtrace(2);
// error message to be displayed, logged or mailed
$error_message = "\nERRNO: $errNo \nTEXT: " . $errStr . " \n" .
"LOCATION: " . $errFile . ", line " . $errLine . ", at
" .
date("F j, Y, g:i a") . "\nShowing backtrace:\n" .
$backtrace . "\n\n";
// email the error details, in case SEND_ERROR_MAIL is true
if (SEND_ERROR_MAIL == true)
error_log($error_message, 1, ADMIN_ERROR_MAIL, "From: " .
SENDMAIL_FROM . "\r\nTo: " . ADMIN_ERROR_MAIL);
// log the error, in case LOG_ERRORS is true
if (LOG_ERRORS == true)
error_log($error_message, 3, LOG_ERRORS_FILE);
// warnings don't abort execution if IS_WARNING_FATAL is false
// E_NOTICE and E_USER_NOTICE errors don't abort execution
if (($errNo == E_WARNING && IS_WARNING_FATAL == false) ||
($errNo == E_NOTICE || $errNo == E_USER_NOTICE))
// if the error is non-fatal ...
{
// show message only if DEBUGGING is true
if (DEBUGGING == true)
echo "<pre>" . $error_message . "</pre>";
}
else
// if error is fatal ...
{
// show error message
if (DEBUGGING == true)
echo "<pre>" . $error_message . "</pre>";
else
echo SITE_GENERIC_ERROR_MESSAGE;
// stop processing the request
exit;
}
}
// builds backtrace message
function dbg_get_backtrace($irrelevantFirstEntries)
{
$s = '';
$MAXSTRLEN = 64;
$traceArr = debug_backtrace();
for ($i = 0; $i < $irrelevantFirstEntries; $i++)
array_shift($traceArr);
$tabs = sizeof($traceArr) - 1;
foreach($traceArr as $arr)
{
$tabs -= 1;
if (isset($arr['class']))
$s .= $arr['class'] . '.';
$args = array();
if (!empty($arr['args']))
foreach($arr['args']as $v)
{
if (is_null($v))
$args[] = 'null';
else if (is_array($v))
$args[] = 'Array[' . sizeof($v).']';
else if (is_object($v))
$args[] = 'Object:' . get_class($v);
else if (is_bool($v))
$args[] = $v ? 'true' : 'false';
else
{
$v = (string)@$v;
$str = htmlspecialchars(substr($v, 0, $MAXSTRLEN));
if (strlen($v) $MAXSTRLEN)
$str .= '...';
$args[] = "\"" . $str . "\"";
}
}
$s .= $arr['function'] . '(' . implode(', ', $args) . ')';
$Line = (isset($arr['line']) ? $arr['line']: "unknown");
$File = (isset($arr['file']) ? $arr['file']: "unknown");
$s .= sprintf(" # line %4d, file: %s", $Line, $File, $File);
$s .= "\n";
}
return $s;
}
?>

There are some constants in this example, but they quite self-
explanatory. Function dbg_get_backtrace is dedicated for user-friendly
output and trace. Hope this helps a bit

Jul 17 '07 #3

P: n/a
Yarco wrote:
Well, friend. Yes, I'm doing PHP. But exception is a traditional
machinism in programming languages. I'm very doubt about this.
In procedure language, we return error code when we meet an error. So
we need to design error code table and judge them in several
statements. Finally they become boring.
But how about use exception in OOP? Did we drop all "return error
code" styles?
If i want to fetch a webpage:

<?php
function fetchPage($url)
{
//...do something

//if the net speed is very slow, cause we can't fetch the page
throw new SlowNetSpeed("page can't be getted");

//if the page is moved
throw new NoPage("page does't exist");

//...do something
}

// so what can i do, if i want the fetchPage procedure go on fetching
when SlowNetSpeed Exception happen?
// it stop when NoPage Exception happen?
while (1)
{
try
{
$c = fetchPage('Some_Where');
// do something
break;
}
catch (SlowNetSpeed $e)
{
}
catch(NoPage $e)
{
break;
}
}
?>
It is very ugly if there exists more Exceptions and other procedure.

Then i'm missing "return error code" style. But i know "return error
code" is not a good method when we deal with error. And exception is
also an ugly grammer when we want to keep code clean.
Exceptions originally were designed to handle unexpected conditions,
i.e. connection to a database failed. They really weren't designed to
replace normal error processing (i.e. userid/password mismatch).

Normal errors are generally handled by the calling routine, but
unexpected conditions may be handled by the immediate caller - or
several layers higher. Exceptions give the ability to handle the
condition as high in the calling hierarchy as you need to, without
having to pass return codes from each routine in the which has been called.

I still use them in this way, and it works well.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Jul 17 '07 #4

P: n/a
Jerry Stuckle wrote:
Exceptions originally were designed to handle unexpected conditions,
i.e. connection to a database failed. They really weren't designed to
replace normal error processing (i.e. userid/password mismatch).

Normal errors are generally handled by the calling routine, but
unexpected conditions may be handled by the immediate caller - or
several layers higher. Exceptions give the ability to handle the
condition as high in the calling hierarchy as you need to, without
having to pass return codes from each routine in the which has been called.

I still use them in this way, and it works well.
I agree. And for errors that should just be debugged a custom error
handler can output a nice walkback (if under development) or log it with
usefull info (if in production).

Greetings,

Henk,
www.phpPeanuts.org.
Jul 17 '07 #5

P: n/a
Erm...I'm thinking about the differences between error table and
exception.
It seems only one difference -- Exception can be caught in high level.

Do you mean we need to use them togather?

On Jul 17, 8:16 pm, Jerry Stuckle <jstuck...@attglobal.netwrote:
Yarco wrote:
Well, friend. Yes, I'm doing PHP. But exception is a traditional
machinism in programming languages. I'm very doubt about this.
In procedure language, we return error code when we meet an error. So
we need to design error code table and judge them in several
statements. Finally they become boring.
But how about use exception in OOP? Did we drop all "return error
code" styles?
If i want to fetch a webpage:
<?php
function fetchPage($url)
{
//...do something
//if the net speed is very slow, cause we can't fetch the page
throw new SlowNetSpeed("page can't be getted");
//if the page is moved
throw new NoPage("page does't exist");
//...do something
}
// so what can i do, if i want the fetchPage procedure go on fetching
when SlowNetSpeed Exception happen?
// it stop when NoPage Exception happen?
while (1)
{
try
{
$c = fetchPage('Some_Where');
// do something
break;
}
catch (SlowNetSpeed $e)
{
}
catch(NoPage $e)
{
break;
}
}
?>
It is very ugly if there exists more Exceptions and other procedure.
Then i'm missing "return error code" style. But i know "return error
code" is not a good method when we deal with error. And exception is
also an ugly grammer when we want to keep code clean.

Exceptions originally were designed to handle unexpected conditions,
i.e. connection to a database failed. They really weren't designed to
replace normal error processing (i.e. userid/password mismatch).

Normal errors are generally handled by the calling routine, but
unexpected conditions may be handled by the immediate caller - or
several layers higher. Exceptions give the ability to handle the
condition as high in the calling hierarchy as you need to, without
having to pass return codes from each routine in the which has been called.

I still use them in this way, and it works well.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstuck...@attglobal.net
==================

Jul 18 '07 #6

P: n/a
Yarco wrote:
On Jul 17, 8:16 pm, Jerry Stuckle <jstuck...@attglobal.netwrote:
>Yarco wrote:
>>Well, friend. Yes, I'm doing PHP. But exception is a traditional
machinism in programming languages. I'm very doubt about this.
In procedure language, we return error code when we meet an error. So
we need to design error code table and judge them in several
statements. Finally they become boring.
But how about use exception in OOP? Did we drop all "return error
code" styles?
If i want to fetch a webpage:
<?php
function fetchPage($url)
{
//...do something
//if the net speed is very slow, cause we can't fetch the page
throw new SlowNetSpeed("page can't be getted");
//if the page is moved
throw new NoPage("page does't exist");
//...do something
}
// so what can i do, if i want the fetchPage procedure go on fetching
when SlowNetSpeed Exception happen?
// it stop when NoPage Exception happen?
while (1)
{
try
{
$c = fetchPage('Some_Where');
// do something
break;
}
catch (SlowNetSpeed $e)
{
}
catch(NoPage $e)
{
break;
}
}
?>
It is very ugly if there exists more Exceptions and other procedure.
Then i'm missing "return error code" style. But i know "return error
code" is not a good method when we deal with error. And exception is
also an ugly grammer when we want to keep code clean.
Exceptions originally were designed to handle unexpected conditions,
i.e. connection to a database failed. They really weren't designed to
replace normal error processing (i.e. userid/password mismatch).

Normal errors are generally handled by the calling routine, but
unexpected conditions may be handled by the immediate caller - or
several layers higher. Exceptions give the ability to handle the
condition as high in the calling hierarchy as you need to, without
having to pass return codes from each routine in the which has been called.

I still use them in this way, and it works well.
Erm...I'm thinking about the differences between error table and
exception.
It seems only one difference -- Exception can be caught in high level.

Do you mean we need to use them togather?
(Top posting fixed)

I use both - which one depends on what I'm doing. If it's an error
which I expect to occur, i.e. "not found" on a database search,
incorrect (or missing) data in an entry field, etc., then I return an
error code. However, if it's an unexpected condition, i.e. unable to
connect to a database which should exist, then I return an exception.

P.S. Please don't top post. Thanks.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Jul 18 '07 #7

P: n/a
Yarco wrote:
Well, friend. Yes, I'm doing PHP. But exception is a traditional
machinism in programming languages. I'm very doubt about this.
In procedure language, we return error code when we meet an error. So
we need to design error code table and judge them in several
statements. Finally they become boring.
But how about use exception in OOP? Did we drop all "return error
code" styles?
If i want to fetch a webpage:
.... snipped...
It is very ugly if there exists more Exceptions and other procedure.

Then i'm missing "return error code" style. But i know "return error
code" is not a good method when we deal with error. And exception is
also an ugly grammer when we want to keep code clean.
Exceptions don't replace conventional error management. On the most
cases i only use exceptions on function/method scope and return FALSE is
a Exception got thrown. In the most cases it's not relevant why the
operation failed for the caller.

<code>
function parse_file($file)
{
try
{
if (!@file_exists($file))
throw new Exception("File does not exist");
if (!$content = @file_get_contents($file))
throw new Exception("Error reading file!");
//do something with content
return $content;
}
catch (Exception $e)
{
//do something with your Exception
return false; //or a error code or a default value
}
}
</code>

I'm using a own Exception class fetching the system error message
(error_get_last, mysql_error, ...) and writing a log file and have a
LastError/LastErrors property for fetching the last error message.
Jul 18 '07 #8

This discussion thread is closed

Replies have been disabled for this discussion.