Link to home
Start Free TrialLog in
Avatar of dbailey01
dbailey01

asked on

Exception getMessage() returns null

I am doing an exercise on try and catch blocks.  I have done up the below code and it does what it's supposed to, except when I try to get the thrown exceptions error message using e.getMessage() I get a null value returned.  This is driving me insane, why am I not getting the proper error message returned?

My code:

public class TryException
{
    public static void main(String[] args)
    {
      for (int i = 0; i < 3; i++)
      {
          int k;
          try
          {
            switch (i)
            {
                case 0:                  // negative array size
                  int a[] = new int[-2];
                  break;
                case 1:                  // null pointer
                  int b[] = null;
                  k = b[0];
                  break;
                case 2:

                  int c[] = new int[2];      // index out of bounds
                  k = c[9];
                  break;
            }
          }
          catch(NegativeArraySizeException e)
          {
            System.out.println("\nTest case #" + i + "\n");
            System.out.println(e.getMessage());
            e.printStackTrace();
          }
          catch(NullPointerException e)
          {
            System.out.println("\nTest case #" + i + "\n");
            System.out.println(e.getMessage());
            e.printStackTrace();
          }
          catch(IndexOutOfBoundsException e)
          {
            System.out.println("\nTest case #" + i + "\n");
            System.out.println(e.getMessage());
            e.printStackTrace();
          }
      }
    }
}
Avatar of sumit_only
sumit_only

This is because the all these exceptions derive from Exception class and which itself derives from Throwable class. The method getMessage() is derived from Throwable class itself. This message is null if the exception object is created with no error message. So, in your case it is that the exceptions hv no error message so, e.getMessage() will anyway return null.

Hope this helps
Sumit
ASKER CERTIFIED SOLUTION
Avatar of InfinityInfinity
InfinityInfinity

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dbailey01

ASKER

Thanks for the response