Home What kind of Exception occurred?
Reply: 1

What kind of Exception occurred?

hoapham Published in 2018-01-13 05:39:56Z

I tried to create a test ClassCastException:

In line 1: it prints out class cast exception as I expected
In line 2: it just prints exception.RuntimeExceptionTest$1B@7852e922 (RuntimeExceptionTest is my class name). I wonder what kind of exception here?

 try {
            class A { }
            class B extends A {}
            class C extends A {}
            A objA = new B();
            System.out.println((C)objA); // Line 1
            System.out.println((A)objA); // Line 2
        } catch (Exception e) {
Max Vollmer
Max Vollmer Reply to 2018-01-13 05:49:22Z

Line2 doesn't throw an exception. From the Oracle javadocs:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

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

That means your Line2 just prints what objA.toString() returns, which is


since exception.RuntimeExceptionTest is your class name.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.342943 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO