0

so I'm quite new to java and I have no idea how this is happening but when I force the program to crash due to stack overflow my catch method appears to catch it but is stuck in an infinite loop, not sure why or how to fix it. Could anybody help me out? I'd really appreciate it.

private static int Fibonacci(int n)
{
    int fibVal = 0;
    try
    {
        if (n == 0)
        {
            fibVal = 0;
        }
        else if (n == 1)
        {
            fibVal = 1;
        }
        else
        {
            fibVal = Fibonacci(n - 1) + Fibonacci(n - 2);
        }
    }
    catch (StackOverflowError e)
    {
        System.out.println("This was another stack overflow, probably too high an input");
    }
Abra
  • 19,142
  • 7
  • 29
  • 41
  • 2
    Put the try-catch where you first call the methd `Fibonacci`, not inside the recursive function – Marek Sebera Aug 14 '20 at 04:07
  • Below catch what are you returning?, As because if you don't return your program will not compile. – John Aug 14 '20 at 04:16
  • You're not suppose to catch an Error. Errors are very bad. It is different than exception – George Aug 14 '20 at 04:47
  • https://stackoverflow.com/questions/912334/differences-between-exception-and-error – George Aug 14 '20 at 04:48
  • I don't understand how method `Fibonacci` compiles because it is supposed to return an `int` but it doesn't return anything. – Abra Aug 14 '20 at 05:01

3 Answers3

1

Get rid of your try/catch blocks entirely. You're not suppose to catch errors.

Differences between Exception and Error

The recursive solution for Fibonacci is very inefficient. You're going to run into StackOverflowError with pretty small numbers like 100. That's just the limitation of your solution. You'd have to implement it using other methods, which you can just find online.

George
  • 2,820
  • 4
  • 29
  • 56
0

Try this. Agree with George, don't use recursion for Fibonacci. Modified your code a bit.

public class Demo{

private static int Fibonacci(int n)
{
    if (n == 0)
    {
        return 0;
    }
    else if (n == 1)
    {
        return 1;
    }
    else
    {
        return (Fibonacci(n - 1) + Fibonacci(n - 2));
    }
}


     public static void main(String []args){
        int result = Fibonacci(8);
        System.out.println(result);
     }
}
Abhishek
  • 763
  • 7
  • 18
-1

Well, when you catch the exception, you should return a value indicating that Fibonacci call failed (example -1). You should then change your code to verify the results of the Fibonacci function calls to ensure all is well, then add them. That should take care of the infinite loop. Otherwise, since you are catching the exception, recursive calls will keep happening and exceptions thrown.

That said, as this seems to be a homework, just get the thing done without worrying about catching a Stackoverflow exception. Moreover, you can increase the amount of stack allocated to the VM using the -Xssn flag.

Tarik
  • 10,810
  • 2
  • 26
  • 40