2

This may be a Java question, or it may be an Eclipse question, I'm not positive.

I'm creating custom View in Android: HelpTextView extends View

I would like to override View.setVisibility(), forcing calls to HelpTextView.setVisibility() to be written inside try-catch (NullPointerException nex) blocks.

I added both a throws declaration to the method (which is what I thought would do the trick) as well as a throw command but no luck. Is this not working because it's simply never going to work (perhaps overriding just doesn't work that way) or am I doing something wrong?

Satheesh Cheveri
  • 3,621
  • 3
  • 27
  • 46
Rich
  • 4,157
  • 5
  • 33
  • 45

3 Answers3

3

NullPointerException is a subclass of RuntimeException. A RuntimeException is an unchecked exception, meaning that you do not need to catch it.

No matter how you declare your method, you cannot force a NullPointerException to be caught.

You can, however, create your own Exception and force that to be caught.

Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
3

You can not override a method and add an exception which is not already declared in super method except RuntimeExceptions.

Max Power
  • 178
  • 1
  • 10
2

You cannot do this because NullPointerException is a RuntimeException, which does not need to be caught by the caller.

Your best approach is to implement your own Exception.

public class HelpTextView extends View {

    public setThisVisibility(boolean isVisible) throws MyNullPointerException {
        ...
    }

}

and your MyNullPointerException cannot be RuntimeException

Beeing Jk
  • 3,796
  • 1
  • 18
  • 29
RamonBoza
  • 8,898
  • 6
  • 36
  • 48