• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception..

 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I got it from
http://www.go4java.20m.com/mock1.htm

public class exception
{
public static void main(String args[])
{
System.out.println("A");
try
{
return; // if i comment this i am getting AC as output
}
catch(Exception e)
{
System.out.println("B");
}

System.out.println("C");

}
}
output:A
here 'c' is not reached,why? and can we return something in void main method?

thanks in advance
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
c would have reached if it was in finally block. Since it is not, so return in try will end the execution of the method.

you can use a simple return statement in void methods i.e. return; you cannot return any value like return 0;//error
 
Hemnathbabu Kottaiveedu
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Preetha,

There are two forms of return statements that can be used depending on whether the method is a void or non void method.
return Statement
Form of return Statement In void Method In Non-void Method

return; optional not allowed

return <expression>; not allowed mandatory

So c is not reached because the flow of execution is transfered to the point from where the main() method has been called.

Hope this helps you!

Thanks
[ November 20, 2008: Message edited by: Hemnathbabu Kottaiveedu ]
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic