Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

can catch have return statement

public String execute() throws Exception{
    try{
        //Do blah
        return "success"; //Assuming everything goes well, return success.
    }catch (Exception e){
        e.printStackTrace();
   return "error"; //???
    }
   return "error"; // can i skip this
}

Open in new window


can we write return statement in the catch block as above?
I never seeing like above.

If yes  can i skip return stmt after catch block.

Please advise
SOLUTION
Avatar of CPColin
CPColin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dpearson
dpearson

You can skip the final return step as long as:

a) You have a return at the end of the try {} block.
b) You catch all exceptions in your catch block.

So yes in this case you can skip it.

Doug
Avatar of gudii9

ASKER

import java.util.*;
import java.lang.*;
import java.io.*;

class Test10
{
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println("Normal operation ouput -");
		System.out.println(Test10.test(false));
		System.out.println("Exceptional output -");
		System.out.println(Test10.test(true));
	}
	
	public static String test(Boolean causeException)
	{
		try
		{
			System.out.println("in try");
			if (causeException)
			{
				throw new Exception();
			}
		}
		catch (Exception e)
		{
			System.out.println("in catch");
			return "return from catch";
		}
		return "returned normally";
	}
}

Open in new window


i got
Normal operation ouput -
in try
returned normally
Exceptional output -
in try
in catch
return from catch


i thought below should print at end

returned normally

please advise
The return from the catch is exiting the method, anything below it will not process.  Which is why when it enters the exceptional branch the last output is - return from catch.

If you were to add a finally block and return from it, then the program would not compile as the line - return "returned normally"; - would not be reachable; e.g.:
import java.util.*;
import java.lang.*;
import java.io.*;

class Test
{
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println("Normal operation ouput -");
		System.out.println(Test.test(false));
		System.out.println("Exceptional output -");
		System.out.println(Test.test(true));
	}
	
	public static String test(Boolean causeException)
	{
		try
		{
			System.out.println("in try");
			if (causeException)
			{
				throw new Exception();
			}
		}
		catch (Exception e)
		{
			System.out.println("in catch");
			return "return from catch";
		}
		finally
		{
			System.out.println("in finally");
			return "return from finally";
		}
		// the following line of code is now unreachable; because of this the program will not compile.
		return "returned normally";
	}
}

Open in new window

However, commenting out the line - return "returned normally"; - allows for the program to be compiled.  Running this new version gives the following output -User generated imageThe reason you get this output is because the finally branch executes *always*.  This is why I started my last comment with -
As a best practice you would not want to return from a catch.
-saige-
Avatar of gudii9

ASKER

let me try
Avatar of gudii9

ASKER

import java.util.*;
import java.lang.*;
import java.io.*;

class Test
{
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println("Normal operation ouput -");
		System.out.println(Test.test(false));
		System.out.println("Exceptional output -");
		System.out.println(Test.test(true));
	}
	
	public static String test(Boolean causeException)
	{
		try
		{
			System.out.println("in try");
			if (causeException)
			{
				throw new Exception();
			}
		}
		catch (Exception e)
		{
			System.out.println("in catch");
			return "return from catch";
		}
		finally
		{
			System.out.println("in finally");
			return "return from finally";
		}
		// the following line of code is now unreachable; because of this the program will not compile.
		//return "returned normally";
	}
}

Open in new window


i too got compilation error at last line
return "returned normally";

when i commented that as above i got output as below
Normal operation ouput -
in try
in finally
return from finally
Exceptional output -
in try
in catch
in finally
return from finally
Avatar of gudii9

ASKER

import java.util.*;
import java.lang.*;
import java.io.*;

class Test
{
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println("Normal operation ouput -");
		System.out.println(Test.test(false));
		System.out.println("Exceptional output -");
		System.out.println(Test.test(true));
	}
	
	public static String test(Boolean causeException)
	{
		try
		{
			System.out.println("in try");
			if (causeException)
			{
				throw new Exception();
			}
		}
		catch (Exception e)
		{
			System.out.println("in catch");
			return "return from catch";
		}
		finally
		{
			System.out.println("in finally");
			return "return from finally";
		}
		// the following line of code is now unreachable; because of this the program will not compile.
		//System.out.println("outside of try catch finally");
		//return "returned normally";
	}
}

Open in new window


i cannot put sysout also as last line?
//System.out.println("outside of try catch finally");
Please advise
Avatar of gudii9

ASKER

i expected output as below

Normal operation ouput -
in try
in finally
return from finally
Exceptional output -
in try
in catch
return from catch
in finally
return from finally

not like below

Normal operation ouput -
in try
in finally
return from finally
Exceptional output -
in try
in catch
in finally
return from finally

i wonder why below not printed

return from catch
Let me try to explain this a different way.

Your expected results do not occur because the block of code encapsulated in the finally branch will *ALWAYS* process.  Since the finally branch includes a return statement, then the return statement in the catch block is ignored.  Whether you believe it or not, this also means that a return statement from the try branch will also be ignored.  Consider the following:
public class Test{

	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println("Normal operation ouput -");
		System.out.println(Test.test(false));
		System.out.println("Exceptional output -");
		System.out.println(Test.test(true));
	}
	
	public static String test(Boolean causeException)
	{
		try
		{
			System.out.println("in try");
			if (causeException)
			{
				throw new Exception();
			}
			return "return from try";
		}
		catch (Exception e)
		{
			System.out.println("in catch");
			return "return from catch";
		}
		finally
		{
			System.out.println("in finally");
			return "return from finally";
		}
		// the following line of code is now unreachable; because of this the program will not compile.
		// return "returned normally";
	}
}

Open in new window

Which produces the following output:User generated imageSince the finally is returning the results, then every statement following the end of the finally branch is rendered unreachable.  This means that your attempt to print to the console is ignored because you have returned from the method.

Ultimately though, I refer you back to my original statement:
As a best practice you would not want to return from a catch.
-saige-
Avatar of gudii9

ASKER

As a best practice you would not want to return from a catch.
How about try and finally? can we return from those ? please advise
Avatar of gudii9

ASKER

Your expected results do not occur because the block of code encapsulated in the finally branch will *ALWAYS* process.  Since the finally branch includes a return statement, then the return statement in the catch block is ignored.  Whether you believe it or not, this also means that a return statement from the try branch will also be ignored

i do not know this. so we can only have one return statement from method right?
if return is there in finally already then it is useless to have in try , catch right
Whether it is legal or not depends upon the language (Java allows for you to return from a finally whereas C# does not).  However lets consider the *smell* of this (or the artifact otherwise).
public class Test{

     public static void main(String []args){
        System.out.println("Artifact Producing Practices");
        System.out.println(Test.ArtifactAdd(2, 2));
        System.out.println(Test.ArtifactAdd(10, 1));
        System.out.println("Best Practices");
        System.out.println(Test.BestPracticeAdd(2, 2));
        System.out.println(Test.BestPracticeAdd(10, 1));
     }
     
     public static String ArtifactAdd(int lhs, int rhs)
     {
         try
         {
             if (lhs % 10 != 0 || rhs % 10 != 0)
             {
                 return lhs + " + " + rhs + " = " + (lhs + rhs);
             }
             else
             {
                 throw new Exception();
             }
         }
         catch (Exception e)
         {
             // In all honesty we should never ever ever get here, but for the sake of argument a parameter that is divisible by 10 requires special treatment.
             return lhs + " + " + rhs + " = " + (lhs + rhs);
         }
         finally
         {
             return "2 + 2 = " + (2 + 2);
         }
     }
     
     public static String BestPracticeAdd(int lhs, int rhs)
     {
         String result = "";
         try
         {
             if (lhs % 10 != 0 || rhs % 10 != 0)
             {
                 result = lhs + " + " + rhs + " = " + (lhs + rhs);
             }
             else
             {
                 throw new Exception();
             }
         }
         catch (Exception e)
         {
             // In all honesty we should never ever ever get here, but for the sake of argument a parameter that is divisible by 10 requires special treatment.
             result = lhs + " + " + rhs + " = " + (lhs + rhs);
         }
         finally
         {
             if (lhs % 10 == 0 || rhs % 10 == 0)
             {
                 result = "Special treatment applied - " + result;
             }
         }
         return result;
     }
}

Open in new window

Produces the following results -User generated imageOn the outside we can look at this and say, why that makes no sense whatsoever, why would I forcibly return a result that is improper, to which there may be a perfectly valid reason.  However, by the standards of best practices or recommended practices or even just logic in general, you would want to perform the following steps:

1. Declare and initialize a result variable.

2. *[b]Try[/b]* to do something to your result variable (using parameters if needed).

3. *[b]Catch[/b]* any exceptional behaviour.

In catching exceptional behaviour you have to decide if the exceptional behaviour affects the result variable or output of your method and act accordingly

4. *[b]Finally[/b]*, perform any tasks to complete the operation.

In general this includes cleanup/destruction/disposal of any objects that are no longer required (obviously not including anything that the returned object [your result variable] depends upon).  Ultimately though, this is optional, you do not have to have a finally step as finally is generally regarded as a cleanup routine, or something that you want to always happen no matter whether the try processes normally or an exceptional course is taken.

5. Return your result variable.

-saige-
Avatar of gudii9

ASKER

Artifact Producing Practices
2 + 2 = 4
2 + 2 = 4
Best Practices
2 + 2 = 4
Special treatment applied - 10 + 1 = 11

i got output as above when i ran as below
public class Test{

     public static void main(String []args){
        System.out.println("Artifact Producing Practices");
        System.out.println(Test.ArtifactAdd(2, 2));
        System.out.println(Test.ArtifactAdd(10, 1));
        System.out.println("Best Practices");
        System.out.println(Test.BestPracticeAdd(2, 2));
        System.out.println(Test.BestPracticeAdd(10, 1));
     }
     
     public static String ArtifactAdd(int lhs, int rhs)
     {
         try
         {
             if (lhs % 10 != 0 || rhs % 10 != 0)
             {
                 return lhs + " + " + rhs + " = " + (lhs + rhs);
             }
             else
             {
                 throw new Exception();
             }
         }
         catch (Exception e)
         {
             // In all honesty we should never ever ever get here, but for the sake of argument a parameter that is divisible by 10 requires special treatment.
             return lhs + " + " + rhs + " = " + (lhs + rhs);
         }
         finally
         {
             return "2 + 2 = " + (2 + 2);
         }
     }
     
     public static String BestPracticeAdd(int lhs, int rhs)
     {
         String result = "";
         try
         {
             if (lhs % 10 != 0 || rhs % 10 != 0)
             {
                 result = lhs + " + " + rhs + " = " + (lhs + rhs);
             }
             else
             {
                 throw new Exception();
             }
         }
         catch (Exception e)
         {
             // In all honesty we should never ever ever get here, but for the sake of argument a parameter that is divisible by 10 requires special treatment.
             result = lhs + " + " + rhs + " = " + (lhs + rhs);
         }
         finally
         {
             if (lhs % 10 == 0 || rhs % 10 == 0)
             {
                 result = "Special treatment applied - " + result;
             }
         }
         return result;
     }
}

Open in new window


i di dnot understand the output what it is saying. please advise
In laymens terms...  When you add 2 + 2, you are supposed to get 4.  This is correct with both methods...

When you add 10 + 1, you are supposed to get 11.  The first method incorrectly returns 2 + 2 = 4 (because of the finally method)...  The second method appends text in front of the correct result (as an example of what a finally can be used for but not needed)...

In all honesty, the second method could be rewritten without the finally...  It's not needed...  An example of a proper Addition method -
public static String Add(int lhs, int rhs)
{
	String result = "";
	try
	{
		result = lhs + " + " + rhs + " = " + (lhs + rhs);
	}
	catch (Exception e)
	{
		result = lhs + " + " + rhs + " could not be determined.";
	}
	return result;
}

Open in new window


-saige-
Avatar of gudii9

ASKER

you mean BestPracticeAdd() should be replaced with Add() as above right.
public class Test{

     public static void main(String []args){
        System.out.println("Artifact Producing Practices");
        System.out.println(Test.ArtifactAdd(2, 2));
        System.out.println(Test.ArtifactAdd(10, 1));
        System.out.println("Best Practices");
        System.out.println(Test.Add(2, 2));
        System.out.println(Test.Add(10, 1));
     }
     
     public static String ArtifactAdd(int lhs, int rhs)
     {
         try
         {
             if (lhs % 10 != 0 || rhs % 10 != 0)
             {
                 return lhs + " + " + rhs + " = " + (lhs + rhs);
             }
             else
             {
                 throw new Exception();
             }
         }
         catch (Exception e)
         {
             // In all honesty we should never ever ever get here, but for the sake of argument a parameter that is divisible by 10 requires special treatment.
             return lhs + " + " + rhs + " = " + (lhs + rhs);
         }
         finally
         {
             return "2 + 2 = " + (2 + 2);
         }
     }
     
     public static String Add(int lhs, int rhs)
     {
     	String result = "";
     	try
     	{
     		result = lhs + " + " + rhs + " = " + (lhs + rhs);
     	}
     	catch (Exception e)
     	{
     		result = lhs + " + " + rhs + " could not be determined.";
     	}
     	return result;
     }
}

Open in new window

when i modified i got below output
Artifact Producing Practices
2 + 2 = 4
2 + 2 = 4
Best Practices
2 + 2 = 4
10 + 1 = 11
Avatar of gudii9

ASKER

In laymens terms...  When you add 2 + 2, you are supposed to get 4.  This is correct with both methods...

When you add 10 + 1, you are supposed to get 11.  The first method incorrectly returns 2 + 2 = 4 (because of the finally method)...

i am bit not clear 2+2 should give 4 only right. why it is incorrect
It is incorrect because it will only return 2 + 2 = 4, regardless of the parameters.

-saige-
Avatar of gudii9

ASKER

public class Test{

     public static void main(String []args){
        System.out.println("Artifact Producing Practices");
        System.out.println(Test.ArtifactAdd(2, 2));
        System.out.println(Test.ArtifactAdd(10, 1));
        System.out.println("Best Practices");
        System.out.println(Test.Add(2, 2));
        System.out.println(Test.Add(10, 1));
     }
     
     public static String ArtifactAdd(int lhs, int rhs)
     {
         try
         {
             if (lhs % 10 != 0 || rhs % 10 != 0)
             {
                 return lhs + " + " + rhs + " = " + (lhs + rhs);
             }
             else
             {
                 throw new Exception();
             }
         }
         catch (Exception e)
         {
             // In all honesty we should never ever ever get here, but for the sake of argument a parameter that is divisible by 10 requires special treatment.
             return lhs + " + " + rhs + " = " + (lhs + rhs);
         }
         finally
         {
             return "2 + 2 = " + (2 + 2);
         }
     }
     
     public static String Add(int lhs, int rhs)
     {
     	String result = "";
     	try
     	{
     		result = lhs + " + " + rhs + " = " + (lhs + rhs);
     	}
     	catch (Exception e)
     	{
     		result = lhs + " + " + rhs + " could not be determined.";
     	}
     	return result;
     }
}

Open in new window


i wonder why i am getting warning as attached. please advise
warning.png
Avatar of gudii9

ASKER

In laymens terms...  When you add 2 + 2, you are supposed to get 4.  This is correct with both methods...

When you add 10 + 1, you are supposed to get 11.  The first method incorrectly returns 2 + 2 = 4 (because of the finally method)...

i am not clear on why first method is incorectly returning 4 instead of 11 due to finally. I have not understood this. please advise
Avatar of gudii9

ASKER

is it becuase in case of first method finally has return so the return from try and return from catch are ignored and all the time return from finally only called whether code flow goes to try or catch block .
Is my above understanding is correct. please advise
Refer to: http:/Q_28660752.html#a40739072 and http:/Q_28660752.html#a40763444
...the finally branch executes *always*...
You are really overthinking this.  It is a simple concept.  You try to do something (*TRY*)...  In case of a failure you do something else (*CATCH*)...  Regardless of which task you complete you always do this (*FINALLY*)...

-saige-
Avatar of gudii9

ASKER

It is a simple concept.  You try to do something (*TRY*)...  In case of a failure you do something else (*CATCH*)...  Regardless of which task you complete you always do this (*FINALLY*)...

i got above clearly.


Since the finally branch includes a return statement, then the return statement in the catch block is ignored.  Whether you believe it or not, this also means that a return statement from the try branch will also be ignored.  

Above is bit new to me. Based on above explanation now understand why i got below output


Artifact Producing Practices
2 + 2 = 4
2 + 2 = 4
Best Practices
2 + 2 = 4
10 + 1 = 11