Sandeep Roy Sandeep Roy - 5 months ago 8
Java Question

Java Exception Handling understanding issue

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");
}
}
}

Answer

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.

Comments