-1

As reference Id of an object prints the className@hash , so how does, e (a reference id of Exception class's object) prints the exception name?

class try1{
    public static void main(String ...args){
    try{
        int x = 10/0;
        System.out.print(x);
    }catch(ArithmeticException e){
        System.out.print(e);
    }

    }
}
tramboo
  • 25
  • 6
  • You can override the `toString()` method in your `class` which allows you to return any `String` you'd like. In case of `Exceptions` they just return their class and the message. In case of `Integer`s they return their value in base 10 etc. For more explanation read the [duplicate] link – Lino May 07 '19 at 12:03
  • Your code should not print something className@hash? It will print java.lang.ArithmeticException: / by zero – Amit Bera May 07 '19 at 12:07
  • so actually exception classes overrides the toString method of Object class, and prints the exception? Am i right? – tramboo May 07 '19 at 12:08
  • yeah Amit Bera, thats my question? Why does it print java.lang.ArithmeticException: / by zero – tramboo May 07 '19 at 12:08
  • it's `Throwable` who override the toString in the hierarchy of ArithmaticException – Amit Bera May 07 '19 at 12:09
  • Thank You Lino , i understood it now. – tramboo May 07 '19 at 12:11

1 Answers1

-1

When you use any object in java System.out.println(object); It will always call java object.toString() method.

Throwable class is overriding the toString() method to display information for all exceptions. As all exceptions are sub classes for throwable class, exceptions will be displayed in className:message format.

Internal implementation of toString() method in Throwable class.

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

In your case ArithmeticException extends RuntimeException, RuntimeException extends Exception and Exception extends Throwable. As ArithmeticException, RuntimeException and Exception classes are not overriding toString() method. That's why Throwable toString() method is executed.

If Throwable also not override the toString() then it will execute the toString() of java.lang.Object which has default implementation like below

 public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
 }
gprasadr8
  • 789
  • 1
  • 8
  • 12