0

i am new in java i don not understand that why exception class reference variable print the message and reference variable of normal class print the eclassname@jsjka why ?

public class Exception11 {
    int x,y;

    public static void main(String[] args) {
        try{
        int total;
        Exception11 e=new Exception11();
        e.x=10;
        e.y=0;
        total=10/0;
        System.out.println("Value of refernce variable: "+e);
        System.out.println(total);
        } catch (ArithmeticException h) {
            System.out.println("number can not divide by the 0 Please try again");
            int total;
            Exception11 e=new Exception11();
            System.out.println("Value of refernce variable: "+e);
            System.out.println("Value of refernce variable: "+h);



        }

    }

}

answer -----------------------------

number can not divide by the 0 Please try again
Value of refernce variable: Exception11@4f1d0d
Value of refernce variable: java.lang.ArithmeticException: / by zero
Amir Pashazadeh
  • 7,170
  • 3
  • 39
  • 69
anil
  • 143
  • 2
  • 4
  • 13

4 Answers4

4

You're seeing the Object#toString representation of your class. In contrast ArithmeticException already overrides this method. You need to override this method in Exception11

@Override
public String toString() {
    return "Exception11 [x=" + x + ", y=" + y + "]";
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

Calling System.out.println("..." + e) will invoke the toString() method of Exception11 e. Since the Exception11 class doesn't have a toString() method, it inherits Object's toString() method, which returns a String with the value:

getClass().getName() + '@' + Integer.toHexString(hashCode())

This is where Exception11@4f1d0d comes from. You must implement toString() in your Exception11 class and have it return whatever string you want the error to be named.

See Object#toString() for details on the Object's toString() method.

arshajii
  • 127,459
  • 24
  • 238
  • 287
asaini007
  • 858
  • 5
  • 19
1

You're printing h.toString() and e.toString(). Since ArithmeticException has an overridden custom toString that is printed.

With your class, the default is printed, namely the class name followed by @ followed by the identity hash code in hex.

You can override as:

@Override
public String toString() {
    //your logic to construct a string that you feel
       // textually represents the content of your Exception11
}
nanofarad
  • 40,330
  • 4
  • 86
  • 117
1

ArithmeticException uses Throwable#toString() implementation:

public String toString() {
    String s = getClass().getName();
    String message = getLocalizedMessage();
    return (message != null) ? (s + ": " + message) : s;
}

while your class Exception11 uses the default Object#toString():

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417