let's say, i have 50 lines of javascript statements in a block. is there a way that the script continues to run if any one of the lines got an error, without using a lot of try catch blocks for each of the line?
Asked
Active
Viewed 7,702 times
0
-
1you have to use global error handing like , read this question http://stackoverflow.com/questions/951791/javascript-global-error-handling – dev.meghraj Apr 12 '13 at 06:57
-
1@karaxuna Sometimes you expect errors to occur. – Moritz Roessler Apr 12 '13 at 08:45
-
@C5H8NNaO4 In very rare cases, he can use try, but i believe that everything can be considered on client side javascript. I don't know, maybe i'm wrong... – karaxuna Apr 12 '13 at 08:57
2 Answers
1
Try this:
1: <head>
2: <script language="javascript">
3: function stoperror()
4: {
5: return true
6: }
7: window.onerror=stoperror();
8: </script>
9: </head>

Fabiotocchi
- 226
- 3
- 11
-
2doesn't work.. the script halts. by the way https://developer.mozilla.org/en-US/docs/DOM/window.onerror says "Note that some/many error events do not trigger window.onerror, you have to listen for them specifically."... what exactly are those errors? – konghou Apr 12 '13 at 07:34
-
Try catch seems the only way then... http://stackoverflow.com/questions/2978291/on-error-resume-next-in-javascript – Fabiotocchi Apr 12 '13 at 07:46
1
Your question is a bit questionable. If you have 50 statements in a block which you allow to fail independently I conclude than that there is no relation between those statements. In this example
var a = 1;
var b = a + 2;
the b variable relies on the outcome of a. If thats not the case, I assume, the only reason that those statements are placed in one block is that they must be executed at the same time. In that case, I also assume that those statements are more expressions like functions with side-effects, like C#-void functions or Actions. You don't really care about the outcome of the expressions..
You need to put each expression in a try-[catch | finally] block, I have no other option. To make it less verbose you can do something like below:
var tryF = function() {
// convert arguments to normal array
var args = [].slice.call(arguments, 0, arguments.length);
// if has function to execute
if(args.length > 0)
{
var func = args[0];//alert(func);
try {func();}
finally {
// if has next function to execute
if(args.length>1) {
tryF.apply(null, args.slice(1, args.length));
}
}
}
}
// usage
{
// first function has a error, it won't block the next
tryF(function() { aslert(1); }, function() { alert(1); });
}

Andries
- 1,547
- 10
- 29
-
in my case i have a lot of operations to deal with complex objects such as: var a = b.c.d .... here properties b,c,d maybe undefined but that's alright with my operations. however i need to either perform a lot of checking on each of those objects (say if(b!=undefined && b.c!=undefined...) and so on) or put the statement in a try { var a = b.c.d... } block which is too clumsy. – konghou Apr 12 '13 at 09:38