473,395 Members | 1,471 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,395 software developers and data experts.

A better alternative to try catch block? Pretty Please?

Is there a more concise way to do something like the the
desired code below?

The gripe is with the try-catch syntax. It takes *way* too
many lines of code to evaluate a conditional expression
when zero or more parts of the conditional expression may
trigger an error. In this case, the trigger is a call to
a non-defined (null) object.

In other words, how can you do a more simple 'try' statement
that simply spits out true or false, depending on whether
the 'tried' code threw an error or not?

Defining a function don't seem to work because you
can't pass the 'try' code as an argument. Extending the
'Global' constructor is not an option, so now what?

Any suggestions? TIA.
/// desired code (YAAY!) :) --------------------------------

if ( try(Meth.random) && try(Myth.random) && try(Math.random) )
{
/// do something
}
/// existing code (YUUK!) :( --------------------------------

var bTmp;
var bOkMeth;
try{Meth.random;
bTmp=true;}catch(e){bTmp=false;} bOkMeth = bTmp;

var bOkMyth;
try{Myth.random;
bTmp=true;}catch(e){bTmp=false;}bOkMyth = bTmp;

var bOkMath;
try{Math.random;
bTmp=true;}catch(e){bTmp=false;}bOkMath = bTmp;

if (bOkMeth && bOkMyth && bOkMath)
{
/// do something here
}
Jul 23 '05 #1
3 3348
On 1 Apr 2004 13:52:09 -0800, valued customer <sc******@hotmail.com> wrote:
Is there a more concise way to do something like the the
desired code below?
[snip]
/// desired code (YAAY!) :) --------------------------------

if ( try(Meth.random) && try(Myth.random) && try(Math.random) )
{
/// do something
}


// Define outside a function
var global = this;

function isDefined( r ) {
return( 'undefined' != typeof r );
}
...
...
if(( isDefined( global['Meth']) && Meth.random ) &&
( isDefined( global['Myth']) && Myth.random ) &&
( isDefined( global['Math']) && Math.random ))
{
// all exist
}

If random is a method, that should work fine. If it's a property that
could evaluate to false[1], you'd have to use isDefined() on that, too.

Is that better?

Mike

[1] Boolean false, null, "" (empty string), or 0. Best avoid undefined as
a valid value.

--
Michael Winter
M.******@blueyonder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 23 '05 #2
sc******@hotmail.com (valued customer) writes:
The gripe is with the try-catch syntax. It takes *way* too
many lines of code to evaluate a conditional expression
when zero or more parts of the conditional expression may
trigger an error. In this case, the trigger is a call to
a non-defined (null) object.
Exeptions should be ... well, the exception. Using them as
conditionals is misusing them.
In other words, how can you do a more simple 'try' statement
that simply spits out true or false, depending on whether
the 'tried' code threw an error or not?
if you have more than expression that necessarily throws exceptions,
you'll just have to endure. That should rarely be the case.
/// desired code (YAAY!) :) --------------------------------

if ( try(Meth.random) && try(Myth.random) && try(Math.random) )
{
/// do something
}

What would Meth.random throw? Why not
if ( (typeof Meth!="undefined" && Meth.random) &&
(typeof Myth!="undefined" && Myth.random) &&
(typeof Math!="undefined" && Math.random)) {
// ...
}
(maybe test against "null" too, if needed)

or, using window as a reference to the global object:
if (window.Meth && Meth.random &&
window.Myth && Myth.random &&
window.Math && Math.random) {
//...
}
/// existing code (YUUK!) :( --------------------------------

var bTmp;
var bOkMeth;
try{Meth.random;
bTmp=true;}catch(e){bTmp=false;} bOkMeth = bTmp;


Well, you don't need the temporary variable. Just assign
directly to bO

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #3
> > The gripe is with the try-catch syntax. It takes *way* too
many lines of code to evaluate a conditional expression
when zero or more parts of the conditional expression may
trigger an error.

Exeptions should be ... well, the exception. Using them as
conditionals is misusing them.


Well, that's one way to look at it, although that particular
viewpoint may be sidestepping the issue here. So far, the
suggestions (to paraphrase):

1) start from a globally scoped variable that you know exists;
2) make appropriate tests against 'null' and undefined; and
3) you shouldn't have to do this sort of thing very much ...

make sense I suppose, but do not really address the point ...

/// here is concrete example ---------------------------------

/// the user is allowed to supply oData in numerous different ways

var oData;
//oData = ['#ff0000','#00ff00','#0000ff']; // one way
//oData = {stripe:'red white blue'}; // another
//oData = {stripe:['pink', 'azure', 'mauve']}; // yet another
//oData = {colors:{stripe:['ruby', 'topaz', 'gold']}}; // yet another

var aryFavoriteColors;
aryFavoriteColors =(oData.constructor == Array) ? oData
:(oData.stripe.constructor == String) ? oD[...]split(/\s+/)
:(oData.stripe.constructor == Array) ? oData.stripe
:(oData.colors.constructor == Object &&
oData.colors.stripe.constructor == Array) ? oData.colors.stripe
: ['green', 'blue', 'white']
;

try{ alert(aryFavoriteColors[0]); }catch(e){}
try{ WScript.Echo(aryFavoriteColors[0]); }catch(e){}
try{ Console.writeln(aryFavoriteColors[0]); }catch(e){}
try{ response.write(aryFavoriteColors[0]) }catch(e){}

// This script runs some of the time, and produces errors other times,
// depending on which format of 'oData' the user ultimately submits.

// To make it error-proof, you have to add a lot of try-catch stuff
// (YUUK!!) Why can't I just say 'try one of these options, if *none*
// of them works, don't give me any error messages or throws or popups.
// Away of that! Just give me the default value ...
// ['green','blue','white']

The original request was for a more elegant way to construct a
*conditional* ... the try-catch-throw debate is largely irrelevant.

Given these circumstances ...

1) The application is dealing with a large, heterogeneous and
potentially complicated object heirarchy; (aka DOM; DHTML; XML)
2) The exact structure of that heirarchy is potentially uknown
until runtime (aka user can modify everything); AND
3) The user has (or demands) the flexibility to define the semantics
of the hierarchy according to their own personal preferences (aka
mutliple ways to express the same thing).
4) The application needs the flexibility to run in different contexts
without laborious and bug-prone rewrites.

.... It seems quite reasonable to expect someone would want to use
conditionals in this way.

By the way, another option, enclosing the conditional
inside separate try block, just like with the last few lines
in the example code
above. Yes, that works (sorta), but again, you still have to
segment the code
into little 'try-catch' islands. When all you really want is
to do a simple 'if' statement without mucking around with
catches and throws!

anyway, thanks for the suggestions ...
Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Erik Cruz | last post by:
Hi. I have read several articles recommending avoid to raise exceptions when possible, since exceptions are expensive to the system. Removing code from Try... Catch blocks can help performance?...
3
by: Sai Kit Tong | last post by:
I posted for help on legacy code interface 2 days ago. Probably I didn't make it clear in my original mail. I got a couple of answers but none of them address my issues directly (See attached...
37
by: clintonG | last post by:
Has somebody written any guidelines regarding how to determine when try-catch blocks should be used and where their use would or could be considered superfluous? <%= Clinton Gallagher...
18
by: Simon | last post by:
I was of the impression that code placed after a Try...Catch block was only executed if there was no exception thrown. I've got some VB.net code as part of a Windows form that executes even...
34
by: Bob | last post by:
Hi, The compiler gives Warning 96 Variable 'cmdSource' is used before it has been assigned a value. A null reference exception could result at runtime. Dim cmdSource as SQlClient.SQLDataReader...
32
by: cj | last post by:
Another wish of mine. I wish there was a way in the Try Catch structure to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I...
4
by: Fred | last post by:
Is it possible to use throw in javascript without try..catch? As far as I know, you must call it from within a try..catch block, or the function that calls throw must itself be called from within...
2
by: Carol | last post by:
Exception may be thrown in the code inside the try block. I want to handling the SqlException with State == 1 in a special way, and for all others I want to use a general way to handle. Which of...
4
by: cj | last post by:
my old code Try Dim sw As New System.io.StreamWriter(fileName, True) sw.WriteLine(strToWrite) sw.Close() Catch End Try my new code
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.