Custom Exception with same name as JDK Exception

If I create an exception example IOException, will there be an conflict with the existion IOException of JDK?

In a discussion the qustion popped up for a quick response and most us had it. But if someone has confusions, here is a quick explanation.

Lets  create a custom exception IOException as stated below (IOException.java)

package my.test;

class IOException extends Exception
{
IOException()
{
super("MyIOException Has Raised");
}
}

Next lets create a test program to see what happens (TestException.java).

package my.test;

public class TestException {
public static void main(String[] args)
{
try
{
throw new IOException();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}

When we run the TestException.java file we get the following message:

MyIOException Has Raised

Now lets include an import statement to import java.io.IOException class.

package my.test;
import java.io.IOException;

public class TestException {
public static void main(String[] args)
{
try
{
throw new IOException();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}

When we run the TestException.java file we get the following message:

null

Well the answer seems pretty obvious. This time my.test.IOException was not called. Why?
Answer is hidden in classloaders. Once the bootstrap classloader loads the IOException from java.io package

Interesting observatio is that the following is not allowed:

package my.test;

import java.io.IOException;
import my.test.IOException;

public class TestException {
public static void main(String[] args)
{
try
{
throw new IOException();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}

Above gives the compilation error as two classes with same name (even in different packages) cannot be imported. 
Why this could have been the compile time error is that at runtime classloaders can handle to import the appropriate class but by statically importing classes with same name would raise a conflict.

Any further suggestions or agreements.





Comments

Popular posts from this blog

Hibernate: a different object with the same identifier value was already associated with the session

BeanDefinitionStoreException: Failed to parse configuration class: Could not find class [javax.jms.ConnectionFactory]