0

I have the following code :

class Exception
{
    public static void main(String args[])
    {

        int x = 10;
        int y = 0;

        int result;

        try{
            result = x / y;
        }
        catch(ArithmeticException e){
            System.out.println("Throwing the exception");
            throw new ArithmeticException();
        }
    }
}

The name of the class is 'Exception'. This is the same as java.lang.Exception which is imported by default into the program. Then why does this program compile with two classes having effectively the same name?

kauray
  • 739
  • 2
  • 12
  • 28

3 Answers3

3

Why does this program compile with two classes having effectively the same name?

They have the same simple name. However, their names (fully-qualified names, which include the package declarations) are different.

The way you've defined it, your code doesn't compile, unless your class is located in the project's default package. Your type (Exception) hides the one defined in the java.lang package and since your type is not sub-type of Throwable, the compiler raises an error:

No exception of type Exception can be thrown; an exception type must be a subclass of Throwable

If you want to specify that java.lang.Exception should be caught, then you have to use the fully-qualified name, as there are naming conflicts otherwise:

class Exception {
    public static void main(String args[]) {

        int x = 10;
        int y = 0;

        int result;

        try {
            result = x / y;
        } catch (ArithmeticException e) {
            System.out.println("Throwing the exception");
            throw new ArithmeticException();
        } catch (java.lang.Exception ae) {
            System.out.println("Caught the rethrown exception");
        }
    }
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

Java allow same name of class in different package.

In your example:

Exception class is in default package of your application.

java.lang.Exception is in java.lang package.

Thats why your code compiled if you try to make same class name in same class then compiler show you error.

Bhuwan Prasad Upadhyay
  • 2,916
  • 1
  • 29
  • 33
0

Java Compiler only complain if you have used keyword as an "identifier".

In java Same name class you can re-declare but only constrain is, it must be in the different packages.

Here, In your case,

you class name Exception allowed by compiler because it reside into different package rather then java.lang.

So, at time of compile,

compiler just checks whether same class into same package or not. If found then compiler complain like, already exist otherwise won't.

Vishal Gajera
  • 4,137
  • 5
  • 28
  • 55