Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception not thrown Java

Tags:

java

class ex1
{
    static void my() {
        System.out.println("asdsdf");
    }

    public static void main(String args[]) {

        try {
            for (;;) {
                my();
            }
        } catch (Exception e)//Exception is not caught //Line 1
        {
            System.out.println("Overflow caught");
        } finally {
            System.out.println("In Finally");
        }
        System.out.println("After Try Catch Finally...");

    }
}

The catch statement (Line 1) does not handle the overflow exception as such the output keeps on printing "asdsdf" without throwing an exception. Can anyone tell me why an infinite loop is not handled as an exception ?. Or that's the way it's designed and supposed to work ?

like image 242
UnderDog Avatar asked Dec 04 '25 11:12

UnderDog


1 Answers

An exception is not caught because it is never thrown. Your method does nothing to cause an OverflowException.

An infinite loop is perfectly legal in Java. It will continue running indefinitely. Your loop is also not building more and more resources, it is simply calling a single method which self destructs every iteration after printing to the standard output. It could run forever.

If you, for example, had the method my(); ITSELF simply call my(), then you would immediately get a StackOverflowError, but this would happen on the very first iteration of your for(;;) loop.

like image 112
Kon Avatar answered Dec 07 '25 00:12

Kon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!