Varun
Varun

Reputation: 3311

Exception not thrown 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 ?

Upvotes: 3

Views: 5336

Answers (4)

Kon
Kon

Reputation: 10810

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.

Upvotes: 8

Shuhail Kadavath
Shuhail Kadavath

Reputation: 448

Your method just creates an infinite loop and calls a method . Since no exceptions are thrown you aren't seeing any .

Upvotes: 0

Blessed Geek
Blessed Geek

Reputation: 21614

To create an "overflow" condition, you actually have to cause something to overflow. Like a variable.

Modify your for statement to increment something but do not place any constraint on the continuity of the loop, then there would be an integer overflow.

for (int i=0;;i++) {
}

Alternatively,

for (int i=0;i==i;i++) { // i==i is always true.
}

Another way is to cause a call stack overflow, by recursively calling itself without limit. Each recursive call has to preserve the stack of the preceding recursive call.

Recursive function:

public static my(){
  my();
}

Recursive constructor:

class My {
  My my;
  My() {
     try{
       my = new My();
     }
     catch (Exception e){
        // print exception.
     }
  }
}

Upvotes: 1

Tom
Tom

Reputation: 44811

That's the way it's designed and intended to work - there's this thing called the Halting problem which basically means that would be impossible.

If on the other hand your method was recursive it would consume more and more stack space until an exception was thrown.

Upvotes: 0

Related Questions