Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch encouraged instead of type checking in javascript? [closed]

In python, I've often heard that instead of checking the type of a variable to determine whether you want to do a certain operation on it, you should just wrap the operation in a Try statement and handle the Exception in case you have the wrong input type.

Is the same true of javascript? i.e. should one preferentially use a try / catch approach instead of typeof?

like image 218
foobarbecue Avatar asked May 20 '14 15:05

foobarbecue


1 Answers

However lightweight is exception handling in any language, a rule of thumb is to always use exceptions for checking things that are exceptional.

What I mean it's that if your algorithm needs type checking in normal operation, then it's better to check explicitly the typing using a condition, if the type checking is done to detect to detect abnormal operation, it's better to raise/handle an exception.

Though, as Javascript is loosely typed, most of the time typing problems won't raise an exception, but instead work in a way that you do not always expect...

like image 88
zmo Avatar answered Sep 27 '22 22:09

zmo