I am kinda new with the whole catching-handling exceptions concept and I was wondering why the throws ArithmeticException
doesn't produce an exception error message (in this case/by zero) on exit, but instead during compilation.
Shouldn't it compile normally and then show the error message at the screen? What am I doing wrong?
public class Exception_Tester
{
public static void main(String args[])
{
Exception_Tester et = new Exception_Tester();
int x1;
int x2;
x1 = 5;
x2 = 0;
et.printResults(x1, x2);
}
void printResults(int a, int b) throws ArithmeticException
{
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
}
I executed your code as it is
public class Exception_Tester
{
public static void main(String args[])
{
Exception_Tester et = new Exception_Tester();
int x1;
int x2;
x1 = 5;
x2 = 0;
et.printResults(x1, x2);
}
void printResults(int a, int b) throws ArithmeticException
{
System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));
}
}
And it compiles fine without any error or exception, and as per your requirement, it is throwing ArithmeticException at run time only when System.out.println("Div: "+(a/b));
statement is encountered.
So I don't See any Problem there!