Is it safe to capture stackoverflowerror in Java?

I have two different function implementations (for example, tree size), one recursive and the other explicit stack

Recursion is very fast (probably because it doesn't need to allocate anything on the heap), but it may lead to stack overflow on some "rare" inputs (in the case of a tree, it will appear on any unbalanced tree) The explicit version is slow but unlikely to cause stack overflow

Is it safe to use recursive implementation by default and recover from stackoverflowerror exception by executing explicit implementation?

Is this considered bad practice?

This is a small example of code:

interface Node {
  List<? extends Node> getSons();
}

static int sizeRec (Node root) {
  int result = 1;
  for (Node son : root.getSons()) {
    result += sizeRec(son);
  }
  return result;
}

static int sizeStack (Node root) {
  Stack<Node> stack = new Stack<Node>();
  stack.add(root);
  int size = 0;
  while (! stack.isEmpty()) {
    Node x = stack.pop();
    size ++;
    for (Node son : x.getSons()) {
       stack.push(son);
    }
  }
  return size;
}

static int size (Node root) {
  try {
    return sizeRec(root);
  } catch (StackOverflowError e) {
    return sizeStack(root);
  }
}

Solution

Well, it's a question of opinion But I don't believe you should First of all, your logic distorts the meaning of exception handling ("exception" instead of logic), and other programmers will encounter problems when interpreting your code

In addition, you should not capture "erros", which represents runtime problems in your environment You should ask yourself if it's worth forgetting some good practices Maybe you can try to adjust the runtime configuration to suit the application or put additional verification logic... Where is your call... But considering security, you can't actually say you're good because we don't know how the stack state is. Now, different JRE implementations may be different

Finally, for the bottom problem: This is a bad practice and not safe

come from https://softwareengineering.stackexchange.com/questions/209099/is-it-ever-okay-to-catch-stackoverflowerror-in-java Quotation for:

It has a reason to call it a mistake rather than an exception

From docs:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>