dhineshsundar
dhineshsundar

Reputation: 112

Exception Handling for Anonymous Inner class in Java

I am facing difficulty to handle my own exception from Anonymous Inner class which is a part of Action listener.

Given below is My own Exception:

class Register extends Exception
{
    String Error;
    public Register() 
    {
    Error = new String("Register Exception");
}
}

Here the method given below is in another class in mouse listener.

public void Gui() throws Register
{
    jButton.addMouseListener(new MouseAdapter() 
    {
        public void mouseClicked(MouseEvent e) 
        {
                throw new Register();    //Unhandled exception type Register
         }          
     });
     throw new Register();   // This works fine.
}

And I am able to work if I throw the exception in method.

Upvotes: 0

Views: 4116

Answers (3)

Helium
Helium

Reputation: 368

There are two types of exceptions in Java: Checked (i.e., you are forced to catch them) and unchecked (you are not forced to catch them). Subclasses of RuntimeException and Error are unchecked while subclasses of other exceptions are considered checked. To mitigate the problem in your code change the line

class Register extends Exception

to

class Register extends RuntimeException

Upvotes: 2

Payal
Payal

Reputation: 26

Looking at your code, you will be getting compile time error while throwing your custom exception from mouseClicked method, this is because the method is not throwing your custom exception.

You can handle exception in one of two ways - 1) Use try - catch 2) Or make your method to throw your custom exception.

In your scenario the method mouseClicked is not throwing your custom exception, that is why you are getting the error.

I hope that would help.

Upvotes: 0

kel c.
kel c.

Reputation: 323

Like @Mortiz suggested in the comments, mouseClicked() doesn't have a throws clause. You need to handle the exception inside of mouseClicked().

If you want to get by compiler errors, which is a terrible idea, you can make Register to extend RuntimeException. However, this is probably not what you want. Gui() method will never catch exceptions thrown by mouseClicked() because Gui() is not the caller. mouseClicked() is invoked by the Swing event handling classes.

What you run into is a design problem. If I'm reading this right, you want to handle an exception thrown in response to an input event; and you are expecting a length recovery operation. In such case, you should give feedback to user and fire a thread for recovery operation in mouseClicked().

Upvotes: 0

Related Questions