0

Hi, I am trying to learn creating my exceptions in java.

My classes are :

public class Test {

public static void main(String args[]) {
Test et = new Test();
int x1=5;
int x2=0;

try {
et.printResults(x1, x2);
}
catch (DivideByZeroException dbz) {
System.out.println(dbz.toString());
dbz.printStackTrace();
}
finally {
System.out.println("The numbers are: "+x1+" "+x2);
}
}


void printResults(int a, int b) throws DivideByZeroException {

System.out.println("Add: "+(a+b));
System.out.println("Sub: "+(a-b));
System.out.println("Mul: "+(a*b));
System.out.println("Div: "+(a/b));

throw new DivideByZeroException();
}


}
public class DivideByZeroException extends ArithmeticException 
{
public DivideByZeroException() {}
public DivideByZeroException(String msg) {super(msg);}

public String toString() {
return "DivideByZeroException: The denominator cannot be zero.";
}
}

But the program exits when arrives in a/b what'is wrong ??

Also could someone explain me what is the difference between printStackTrace and toString in an exception object ??

Thanks a lot

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by bufospro
0

It's take place because DivizionByZeroException is ancestor from ArithmeticException, but Java by default throws exactly ArithmeticException.

To prevent throwing ArithmeticException with respect to DivizionByZeroException, you must catch ArithmeticException in printResult() method and manually throw DivizionByZeroException manually.

For example:

public static void main( String[] args ) {
    try {
       float result = x();
    } catch ( XException e ) {
       System.out.println("Exception!"); 
   } finally { System.out.println("Exception?") }
}

private static float x() throws XException {
     try {
        return 1 / 0;
     } catch ( ArithmeticException e ) {
          throw new XException();
     }
}

Edited by nikelin: n/a

0

I really appreciate your help!
Thanks a lot!!

It's take place because DivizionByZeroException is ancestor from ArithmeticException, but Java by default throws exactly ArithmeticException.

To prevent throwing ArithmeticException with respect to DivizionByZeroException, you must catch ArithmeticException in printResult() method and manually throw DivizionByZeroException manually.

For example:

public static void main( String[] args ) {
    try {
       float result = x();
    } catch ( XException e ) {
       System.out.println("Exception!"); 
   } finally { System.out.println("Exception?") }
}

private static float x() throws XException {
     try {
        return 1 / 0;
     } catch ( ArithmeticException e ) {
          throw new XException();
     }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.