Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch a "Maximum call stack size exceeded" error?

  try {
     requestAnimationFrame(function re(){
       re();
     })}
  catch (e){
       console.log(e);
     }

I tried above code in console, it doesn't work as expected. It seems to me that although

 requestAnimationFrame(function re(){
       re();
     })}

will eventually trigger an error, what throws to the try is insteadly the animation's id. How do I catch such a "Maximum call stack size exceeded" error?

like image 763
shenkwen Avatar asked Dec 02 '22 13:12

shenkwen


1 Answers

Maximum call stack size exceeded errors can be caught just like any other errors:

try {
  function recur() { recur(); };
  recur();
} catch (ex) {
  console.log("caught " + ex);
}

What to do in this situation (call stack size exceeded) is not defined in the ECMAScript specification, but in practice, all browsers do throw catchable exceptions. However, lacking a spec different browsers have chosen to throw different types of exceptions: I've seen Error, RangeError and InternalError.

The problem in your code is unrelated to that. The problem is that you're trying to catch exceptions that happen when you call requestAnimationFrame(). But your re() function doesn't run at that point, it runs during the next frame, as you requested. Inside of re(), you can wrap the recursive call to re() and catch the stack overflow exception there instead:

requestAnimationFrame(function re(){
  try {
    re();
  } catch (ex) {
    console.log("caught " + ex);
  }
});
like image 150
Jeremy Avatar answered Dec 04 '22 01:12

Jeremy