Exception not thrown by 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 an overflow exception, because the output continues to print "asdsdf" without raising an exception. Can someone tell me why an infinite loop is not being treated as an exception? Or was it designed and should work?

+4
source share
4 answers

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

The endless loop is completely legal in Java. It will continue indefinitely. Your loop also does not create more resources, it just calls one method, which independently destroys each iteration after printing to standard output. It can go on forever.

If, for example, you used the my(); method my(); ITSELF, just call my() , you will immediately get a StackOverflowError , but this will happen at the very first iteration of your for(;;) loop.

+7
source

To create an overflow condition, you really need to call something overflow. Like a variable.

Modify your for statement to increase something, but do not put any restrictions on the continuity of the loop, then there will be an integer overflow.

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

As an alternative,

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

Another way is to cause the call stack to overflow, recursively calling itself unlimited. Each recursive call must keep a stack of the previous recursive call.

Recursive function :

 public static my(){ my(); } 

Recursive constructor :

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

The way it was intended and intended to work - this thing is called the stopping problem , which basically means that it 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.

0
source

Your method simply creates an infinite loop and calls the method. Since no exceptions are thrown, you do not see them.

0
source

Source: https://habr.com/ru/post/1498111/


All Articles