getMessage( ) when used with exception (i.e. object) prints the message part of the System Defined Message. Lets find out the difference in printing the exception directly and printing the exception by using the getMessage( ) below -
Syntax - exception.getMessage( )
1.Printing the exception directly by using the below statement in catch block -
java.language.ArithmeticException: /by zero
2.Printing the exception by using the getMessage( ) by using the below statement in catch block -
Hence the message part of the System defined Message gets printed when using the getMessage( ) while printing the exception.
Lets implement this on Eclipse IDE -
1. Launch Eclipse IDE, write the following statement in the catch block of 'PrintingExceptions.java' class of 'Project 46' as shown below -
2. Save and Run the Java Class 'PrintExceptions.java' and observe that the above thrown arithmetic exception is handled by printing the following in the output -
Hence getMessage( ) method when used with object of any Exception Class, gets the message part of system defined message of the occurred exception. When used with print statement, prints the message as shown above.
Please comment below to feedback or ask questions.