Reputation: 557
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?
Upvotes: 0
Views: 8069
Reputation: 1527
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); });
}
Upvotes: 1
Reputation: 216
Try this:
1: <head>
2: <script language="javascript">
3: function stoperror()
4: {
5: return true
6: }
7: window.onerror=stoperror();
8: </script>
9: </head>
Upvotes: 1