Reputation: 398
I have written a Java class which throws an exception if supplied with wrong input.
I have written a main program wherein I want if my class called throws an exception then my main class should not display the error message thrown but instead it should display an "Error occurred" string.
My Main program:
public class TestAbstractFunction {
public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractFunction l = new LogFunction();
System.out.print(l+" = ");
System.out.println(l.eval(2));
AbstractFunction si = new SineFunction();
System.out.print(si+" = ");
System.out.println(si.eval(60));
AbstractFunction c1 = null;
for(double i=-10;i<=10;){
try{
c1 = new CompositeFunction(si,l);
}catch(Exception e){
System.out.println("Err");
}
System.out.print(c1+" = ");
double value = c1.eval(i);
value = value + s.eval(i);
System.out.println("f(x) = "+value);
i = i+0.5;
}
}
Method in LogFunction Java class which is throwing illegal argument exception:
// concrete implementation of eval for computing square root
@Override public double eval(double x) throws IllegalArgumentException {
if (x < 0) throw new IllegalArgumentException("Log of negative number is undefined.");
return Math.log10(x);
}
Now am trying to catch this exception in my main method. I have used try catch to do this but compiler just displays illegal argument exception instead of my catch string.
Appreciate your valuable inputs on what I may be doing wrong.
Thanks!!
Upvotes: 0
Views: 2396
Reputation: 640
Yo can put your code like this
for(double i=-10;i<=10;){
try{
c1 = new CompositeFunction(si,l);
System.out.print(c1+" = ");
double value = c1.eval(i);
value = value + s.eval(i);
System.out.println("f(x) = "+value);
i = i+0.5;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Upvotes: 1