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(NegativeArraySizeExc eption e)
{
System.out.println("\nTest case #" + i + "\n");
System.out.println(e.getMe ssage());
e.printStackTrace();
}
catch(NullPointerException e)
{
System.out.println("\nTest case #" + i + "\n");
System.out.println(e.getMe ssage());
e.printStackTrace();
}
catch(IndexOutOfBoundsExce ption e)
{
System.out.println("\nTest case #" + i + "\n");
System.out.println(e.getMe ssage());
e.printStackTrace();
}
}
}
}
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(NegativeArraySizeExc
{
System.out.println("\nTest
System.out.println(e.getMe
e.printStackTrace();
}
catch(NullPointerException
{
System.out.println("\nTest
System.out.println(e.getMe
e.printStackTrace();
}
catch(IndexOutOfBoundsExce
{
System.out.println("\nTest
System.out.println(e.getMe
e.printStackTrace();
}
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks for the response
Hope this helps
Sumit