exception return

class ExceptionReturn
{
public static void main(String[] args)
{
System.out.println(m1());
}
public static getName(){
try
{
System.out.println(10/0);
return 1;
}
catch(ArithmeticException e)
{
return 2;
}
finally{
return 3;
}
}}

Open in new window


i wonder why i got 3 as output not 1,2

class ExceptionReturn2 {
	
	public static void main(String[] args) {

		try {
			System.out.println("try");
			//System.exit(0);
			return;
			//System.exit(0);
		} catch (ArithmeticException e) {
			System.out.println("catch");
		} finally {
			System.out.println("finally");
		}
	}
}

Open in new window


how finally overriding return

System.exit(0); cannot be given after return?

please advise
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CPColinSenior Java ArchitectCommented:
If a finally block is present, it will always be executed. If you have a return statement inside a try block, the code in the finally is executed immediately before the method returns. If that block also has a return statement, that value is returned instead. That's why your first example returns 3 instead of 1 or 2.

In your second example, the code in the finally block is, again, executing immediately before the return statement is executed.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jgleteCommented:
The finally clause executes always, and after the catch if there's one.
The fact is that the first return executes (the finally return), and then the call stack goes up to the main.

System.exit(0) cuts the execution of the program and it's impossible to get into catch or finally.
Manikandan ThiagarajanSenior consultantCommented:
finally class must be executed if exception occurs or not
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

jgleteCommented:
stmani2005: that's not true in the case of System.exit(0).

public class ExceptionExample
{
        public static void main(String[] args)
        {
                try
                {
                        System.out.println("TRY");

                        System.exit(0); //return;
                }
                catch(Exception e)
                {
                        System.out.println(e);
                }
                finally
                {
                        System.out.println("FINALLY");
                }
        }
}

Open in new window


If you execute this code, you WON'T receive "FINALLY" on screen.

If you exchange System.exit(0) by return, then you WILL see "FINALLY" on screen.

You don't have to believe me. Try javac and java this code, and you will see that.
Manikandan ThiagarajanSenior consultantCommented:
Sorry,i didnt noticed system.exit(0) in the code
gudii9Author Commented:
If a finally block is present, it will always be executed. If you have a return statement inside a try block, the code in the finally is executed immediately before the method returns. If that block also has a return statement, that value is returned instead. That's why your first example returns 3 instead of 1 or 2.

actually i am getting some compilation error.


Exception in thread "main" java.lang.Error: Unresolved compilation problem:
      The method m1() is undefined for the type ExceptionReturn

      at simple.servlet.ExceptionReturn.main(ExceptionReturn.java:3)

please advise
CPColinSenior Java ArchitectCommented:
I'm sure you've seen an error like that before. You're calling a method called "m1" and no such method exists.
gudii9Author Commented:
class ExceptionReturn {
	public static void main(String[] args) {
		System.out.println(getName());
	}

	private static char[] m1() {
		// TODO Auto-generated method stub
		return null;
	}

	public static int getName() {
		try {
			System.out.println(10 / 0);
			return 1;
		} catch (ArithmeticException e) {
			return 2;
		} finally {
			return 3;
		}
	}
}

Open in new window


why above gave below output
3


not
1 2 3
CPColinSenior Java ArchitectCommented:
Only one return statement can be executed per method call. Please reread the comments above to see why the one that executed was the one from the finally block.
gudii9Author Commented:
Only one return statement can be executed per method call.
i do not know this rule.
java all about millions of rules which we should always remember in the head
gudii9Author Commented:
If you exchange System.exit(0) by return, then you WILL see "FINALLY" on screen.

what is meaning of exchanging one with other here?
gudii9Author Commented:
public class ExceptionExample
{
        public static void main(String[] args)
        {
                try
                {
                        System.out.println("TRY");

                        System.exit(0); //return;
                }
                catch(Exception e)
                {
                        System.out.println(e);
                }
                finally
                {
                        System.out.println("FINALLY");
                }
        }
}

Open in new window


above gave below output
TRY


public class ExceptionExample
{
        public static void main(String[] args)
        {
                try
                {
                        System.out.println("TRY");

                        //System.exit(0); //return;
                }
                catch(Exception e)
                {
                        System.out.println(e);
                }
                finally
                {
                        System.out.println("FINALLY");
                }
        }
}

Open in new window


above gave
TRY
FINALLY
jgleteCommented:
That's correct.

The usual behavior of try/catch/finally is the following:
  1. The try block is executed.
  2. If one line of the try block throws an Exception, then the flow of the code jumps the first catch block that has the Exception type that corresponds with that Exception.
  3. The finally block is executed always.

The exception to this flow is when you use the System.exit(0) function.
This breaks the flow of the program immediately and this prevents the finally block to be executed.

That's why if you substitute System.exit(0) by return, you see the results of the finally block, and when you use System.exit(0) you can't see the results of the finally block.
CPColinSenior Java ArchitectCommented:
java all about millions of rules which we should always remember in the head

Think of it this way: You call System.out.println() only once, so it can only print one value, right?
gudii9Author Commented:
That's why if you substitute System.exit(0) by return, you see the results of the finally block,

you mean comment line System.exit(0) ?
jgleteCommented:
Yes.

If you comment line System.exit(0), then there's nothing that can prevent the execution of the finally block.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.