JavaScript's untyped function arguments, or: Try...Catch?

Comments

I prefer the following scheme:

1. Check arguments before doing anything else.
2. Use assertion routines that throws an exception if the assertion condition fails

For example:

function doSomething( aJadeObject ){
mustBeDefined(aJadeObject);

//blah blah blah...
}

function mustBeDefined (value) {
if (value == undefined) {
throw new Error(0, 'Value must be defined');
}
}
Do you actually use this? Because the following code simply breaks:

<code>function fx(x){
if( x == undefined ){ throw new Error(0,"Undefined argument."); }
alert(1);
}

fx();

alert(2);</code>

Neither alert's occur. if the fx() call is put into a try...catch then it works fine, but then we're resorting to BOTH manual type checking, and also using try...catch. I could definitely just create a type checking function, like say...

<code>function itemIsType( item, type ){
if( item == undefined ){ throw new Error; }
if( type == undefined ){ throw new Error; }
// etc...
}</code>

But that would reduce the code by at most 2/3rds the number of lines currently being used, and still require that I use a try...catch. If I just use the try...catch by itself, the undefined value errors will be thrown anyway once they're attempted to be used. The only thing this would do is make it possible to prevent ANY code from executing at all unless the types match. Admittedly this could be useful, but how much so I don't know, and I don't think the benefits outway the costs.

That is exactly why I don't use try catch for everything, type checking is more sane.

Post a comment

Already a Vox member? Sign in