Reputation: 9394
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
Upvotes: 0
Views: 61
Reputation: 30648
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();
}
}
}
Upvotes: 3
Reputation: 10747
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 .
Upvotes: 0