Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 22006

Cannot inherit from Exception

Im' trying to write a class BrokenObjectException class derivated from Exception. But in Eclipse I get this error:

The serializable class BrokenObjectException does not declare a static final serialVersionUID field of type long

public class BrokenObjectException extends Exception
{
    BrokenObject(String message)
    {
        ;
    }
}

I have not understood why it asks me to declare a field. Shouldn't interface just force to declare some methods? Anyway I want to have this class because I want to catch it n a different way from how I catch all exceptions, from I example I have a block:

try
{
    if(...)
        throw new Exception("wrong");
    if(...)
        throw new BrokenObjectException("wrong");
}
catch(BrokenObjectException e)
{
    // do something (action1)
    throw e;
}
catch(Exception e)
{
    // so something (action2)
    throw e;
}

So in the first catch block I have written "do something". This because depending on the type of exception thrown I want to do different actions. So since BrokenObjectException is derivated from Exception it shall be catched two times. But if a BrokenObjectException is thrown, I want to do action1 and action2, if just a normal Exception is thrown I want just to do action2.Is that possible? And how to fix the error I'm getting?

Upvotes: 0

Views: 686

Answers (3)

user1223879
user1223879

Reputation: 133

Are you aware why is that serialVersionUID field needed? Is that what you are asking for? if so please look at the following link

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

That's not an error but rather just a warning. Simply use the @SuppressWarnings("serial") annotation just above the class declaration:

@SuppressWarnings("serial")
public class BrokenObjectException extends Exception
{
    BrokenObject(String message)
    {
        ;
    }
}

What is happening is you are extending a class that implements the Serializable interface and so the compiler will warn you if you do not fully comply with its contract. To get around this (since I doubt that you'll want to serialize objects of this class), simply use the annotation above.

Upvotes: 2

dsingleton
dsingleton

Reputation: 1006

I believe that you can just highlight over the error text that eclipse gives you and then tell it to generate the serial version UUID. After that, it should work just how you want it to.

Also you can use the

@SuppressWarnings("serial")

if you want to just ignore it. However, I would recommend going ahead and generating it. For more info on why check out this stack overflow post. What is a serialVersionUID and why should I use it?

Upvotes: 2

Related Questions