Hi,
I am trying to learn exceptions using "throws".
So , my code is

public class A {
public static void main(String args[]) {
A a = new A();
int x1;
int x2;
x1 = 7;
x2 = 0;
a.printer(x1, x2);
}

void printer(int x1, int x2) throws ArithmeticException{

System.out.println("Add: "+(x1+x2));
System.out.println("Sub: "+(x1-x2));
System.out.println("Mul: "+(x1*x2));
System.out.println("Div: "+(x1/x2));
}
}

What is my wrong in div that program exits ??
I use throws ArithmeticException.

Recommended Answers

All 3 Replies

You throw it, but you don't catch it. Exceptions tend to terminate your program in a bad way. You need to catch them so that it won't terminate your program:

public static void main(String args[]) {
A a = new A();
int x1;
int x2;
x1 = 7;
x2 = 0;
  try {
     a.printer(x1, x2);
  } catch (ArithmeticException ae) {
     System.out.println("An error occured: "+ar.getMessage());
  }
}
System.out.println("Finishing the program");

It would appear that although you are thowing the exception (ArithmeticException) you are not dealing with it. If the exception is not handled from where it is called it will be passed up the call stack until something deals with it. Since your program is calling the exception from the main method (and it is not handled there) your program would exit.

To solve this do a try-catch around the printer call. If an exception occurred, then provide some type of error handling (perhaps [in this case] a divide by zero).

Hope that helps

Thanks a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.