0

I'm not able to understand this program. I expect it to output "Hello World", but instead it prints only the "World". I thought that first the try block would execute, printing "Hello" and " ", then afterward when it encounters a 1/0, it would throw an ArithmeticException. The exception would be caught by catch block, then "World" would be printed.

The program is as follows.

 import java.util.*;
 class exception{
     public static void main(String args[]) 
     {
         try
         {
             System.out.println("Hello"+" "+1/0);
         } 
         catch(ArithmeticException e) 
         {
             System.out.println("World");
         }
     }
 }
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
Sandeep Roy
  • 417
  • 6
  • 27
  • 1
    Why do you think it would print `"Hello"` before evaluating `1/0`? – user2357112 Jun 29 '16 at 18:22
  • 1
    It has to interpret the value of `"Hello" + " " + 1/0` before it prints anything. `"Hello"` isn't printed because you aren't saying to print _just_ `"Hello"`, rather `"Hello"` plus something that causes the exception. – Chris Sprague Jun 29 '16 at 18:23

5 Answers5

5

The exception is thrown before calling the println function. The argument value has to be calculated before the function call.

In order for your program to achieve the results you expect, you would edit the code in the try block as follows:

     try
     {
         // this will work and execute before evaluating 1/0
         System.out.print("Hello ");
         // this will throw the exception
         System.out.print(1/0);
     } 
     catch(ArithmeticException e) 
     {
         System.out.println("World");
     }
Chris Sprague
  • 740
  • 1
  • 12
  • 22
Frank Puffer
  • 8,135
  • 2
  • 20
  • 45
1

It does not simply scan the "words" left to right. Everything inside the ( ) needs to be evaluated successfully, and if it is then it gets printed.

It looks at "Hello" and it's fine. Next it looks at 1/0 and creates error.

In the event that the math evaluated successfully it would attempt to concatenate "Hello" and the result. And if that was successful, then it would be printed.

Doug
  • 140
  • 10
1

First "Hello"+" "+1/0 will be evaluated. And then passed as an argument to System.out.println(...). That's why an exception is thrown before System.out.println(...) would have been called.

Shiro
  • 2,610
  • 2
  • 20
  • 36
1

Arguments that are passed in println function/method will be checked first followed by calling of println.So , exception will rise before calling println.Since exception is raise control will go to catch and only "World" will be printed

1

It will checked statement by statement. So, it checks for whole println argument. But, it has an exception, so goes for executing catch block.

NOTE: If it execute first half statement and than checks for Exception, no need remains for try-catch block.