473,387 Members | 1,423 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Exception : an ugly grammer in programming

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
7 1700
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Eric Lilja | last post by:
Hello, I'm working with a hash table that is encapsulated in a class. One of its member functions insert() throws an exception if the insertion fails (for example, if the value was already present...
11
by: Master of C++ | last post by:
Hi, I am writing a simulation package in C++, and so far I've written about 8000 lines of code and have about 30 classes. I haven't used C++ exceptions so far (for various reasons). The only two...
25
by: Peter | last post by:
Hi: I am bored and was wondering: Is it a html page? or
1
by: Paramveer.Singh | last post by:
hi! I tried to extend the grammer for plpgsql by editing postgresql-7.4.3/src/pl/plpgsql/src/gram.y but as soon as you compile it (even without any changes) it gives an error user$ make...
1
by: Paramveer.Singh | last post by:
Hi all! I was looking into the postgres8.0 code for exception handling, and it seems that the grammer treats an exception condition as opt_lblname. This means that I can pass any arbitrary string...
0
by: Gridlock | last post by:
I just started to use this, and am trying to figure out how to set up a generic string parameter in the grammer file. There are many grammer items like integer and others, but I can't find a...
29
by: v4vijayakumar | last post by:
Why there is no overloading (function and operator), function templates and exception handling support in c? after all these are all useful programming constructs. What prevents ANSI/ISO...
23
by: TarheelsFan | last post by:
What happens whenever you throw an exception from within a constructor? Does the object just not get instantiated? Thanks for replies.
0
by: RamyaKarthik | last post by:
can any one guide me how to write programmer for grammer checke using c/c++
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.