Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the catch block produce a compiler error?

I have the following contrived 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();
        }
        catch(Exception ae){
            System.out.println("Caught the rethrown exception");
        }
    }
}

The first catch block rethrows the exception that was caught. The compiler however says "Incompatible Types" and "Throwable" required. Why is this error produced?

like image 563
kauray Avatar asked Dec 14 '22 10:12

kauray


2 Answers

Just change you class name from Exception to Exception1.

It looks like name conflicting issue.

Your Naming convention strategy is Against of Java Identifier define rule.

Means, you can not give name which is already given by library. here, class name.

like image 156
Vishal Gajera Avatar answered Dec 16 '22 22:12

Vishal Gajera


Your Exception class is hiding java.lang.Exception and You are trying to throw your own class as exception. You should throw an object that extends java.lang.Exception class.

Just change Exception with java.lang.Exception

catch(java.lang.Exception ae)

Or change the name of your class which is hiding java.lang.Exception

like image 24
afzalex Avatar answered Dec 16 '22 22:12

afzalex