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?
-
1you have to use global error handing like , read this question stackoverflow.com/questions/951791/…dev.meghraj– dev.meghraj2013-04-12 06:57:52 +00:00Commented Apr 12, 2013 at 6:57
-
1@karaxuna Sometimes you expect errors to occur.Moritz Roessler– Moritz Roessler2013-04-12 08:45:17 +00:00Commented Apr 12, 2013 at 8: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– karaxuna2013-04-12 08:57:32 +00:00Commented Apr 12, 2013 at 8:57
2 Answers
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); });
}
1 Comment
Try this:
1: <head>
2: <script language="javascript">
3: function stoperror()
4: {
5: return true
6: }
7: window.onerror=stoperror();
8: </script>
9: </head>