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

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();
     }
}

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();
     }
}
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.