zoukankan      html  css  js  c++  java
  • java.lang.StackOverflowError exception

    This post shows how to create a StackOverflowError with a recursion. Let’s look at the error message first:
    Exception in thread “main” java.lang.StackOverflowError
    at ch.allenstudy.newway01.Recursion1.f(Recursion1.java:9)
    at ch.allenstudy.newway01.Recursion1.g(Recursion1.java:14)
    at ch.allenstudy.newway01.Recursion1.f(Recursion1.java:9)
    at ch.allenstudy.newway01.Recursion1.g(Recursion1.java:14)

    Here’s the code:
    package ch.allenstudy.newway01;

    public class Recursion1 {
    public int i;

    void f() {
    g();
    }

    void g() {
    f();
    }

    }

    class RecursionTester {
    public static void main(String[] args) {
    Recursion1 n = new Recursion1();
    n.g();
    }
    }

    You can see that f() method calls g() method, then g() calls f(); it’s a recursion.

    Why it gets the StackOverFlow?
    That’s because in the program, the application executes the code one by one.
    {

    myFunct(int a); //Address in memory stack is A
    next line //Address in memory stack is B

    }

    The program make the call to myFunct(int a), this method will be executed. While, after finish execution, the system need send a signal to myFunct(int a), tell it where you should come back and continue. The signal here is called “returned address”; but notice, it’s the return address of “next line”, so that it can continue to run.
    And this “returned address” is pushing into Stack.
    In up sample, you see, the f() and g() call each other in an infinite loop, every time they call each other, there will add a “returned address” into stack.
    After a while, the stack is full. Then have the overflow.

  • 相关阅读:
    多线程学习笔记第一篇
    当Visual Studio中win32控制台应用程序的注释也会生产代码时……
    博客行文及排版技法
    Debian Linux下的Python学习——安装python,vim
    onhashchange事件
    MyEclipse9 Maven开发Web工程 详细配置
    Java面向对象(上)
    lucene 的分析器(analyzer)与分词器(tokenizer)和过滤器(tokenfilter)
    java编程陷阱
    solr中文分词(mmseg4j)
  • 原文地址:https://www.cnblogs.com/backpacker/p/2271194.html
Copyright © 2011-2022 走看看