0

I want to write a class method that returns a value, if the class method has an exception then it will be returned. I'm confused how to decide the class structure for this situation. What I am thinking about is that method returning an Object, if the method executes successfully then it returns a value otherwise an Exception message.

class ABC
{
   public Object xxx(int a,int b)
   {
      Object returnValue=null;
      try{retunValue=a/b;}
      catch(Excetion e){returnValue=e;}            

    return returnValue;
   }

}

Is it the correct way, I was also thinking about setXXX and getXXX methods, but this will not help me for this situation. Please help me, what is the correct approach to follow.

Thanks

Sameek Mishra
  • 8,734
  • 30
  • 90
  • 114

2 Answers2

3

you can throw an exception in catch block when any exception is there. and catch the exception from where you are calling that method

class ABC {

    public static Object xxx(int a, int b) throws Exception{
        Object returnValue = null;
        returnValue = a / b;
        return returnValue;
    }

    public static void main(String a[]){
        try {
            xxx(1, 2);
        } catch(Exception exc) {
            exc.printStackTrace();
        }
    }
}
Alex Abdugafarov
  • 5,772
  • 7
  • 35
  • 58
Hemant Metalia
  • 27,928
  • 18
  • 70
  • 89
0

You would get an arithmetic exception for the above code . You should not throw an Arithmetic Exception, instead throw IllegalArgumentException by checking :-

public int xxx(int a,int b)

{

     if(b==0)
         throw new IllegalArgumentException("Argument divisor is 0");
    else
         return a/b;

}

See this SO Post for details .

Community
  • 1
  • 1
Sandeep Pathak
  • 10,258
  • 7
  • 42
  • 57