1

Please examine my custom exception below:

public class ReportException extends Exception {



    private int mCode = -1;
    private String mString = "";


    public ReportException(int code, String description)
    {
        super(description);
        mCode = code;
        mString = description;
    }


    public int getCode()
    {
        return mCode;
    }


    public String getString()
    {
        return mString;
    }
}

My question is why is this illegal in another class:

try{
       throw new NullPointerException();
   }
catch(ReportException e){

}

To me a NullPointerException is derived from Exception class and so is my custom ReportException so since there the same type i'd expect it can be caught in the catch clause. But my IDE says this is illegal. I had this discussion with a colleague of mine and he said there it cant be done but im just wondering why since they both derive from the same Exception class. This looks to defy polymorphism.

j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • 3
    `"...NullPointerException is derived from Exception class and so is my custom ReportException so since there the same type..."` -- A dog is an animal and so is a cat, but that doesn't mean that a dog is a cat. – azurefrog Jan 22 '15 at 22:30
  • 1
    `NullPointerException` and `ReportException` are both `Exception`s, but `NullPointerException` is not a kind of `ReportException`. In the same way, Germans and Italians are all Europeans, but Germans are not Italians. – John Bollinger Jan 22 '15 at 22:32
  • @immibis False. [Polymorphism.](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) Which is, incidentally, what this question is actually about. – asteri Jan 22 '15 at 22:38

3 Answers3

5

A NullPointerException and your ReportException are both Exceptions, but to catch a ReportException, you must throw a ReportException (or a subclass). A NullPointerException is not a subclass of ReportException, so it's not caught.

Throw a ReportException instead.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

Some code inside the try block has to throw your checked exception before you can explicitly catch it.

This is valid:

try {
    throw new ReportException();
}
catch(ReportException e){
    // handle it
}

See Java: checked vs unchecked exception explanation

Community
  • 1
  • 1
gknicker
  • 5,509
  • 2
  • 25
  • 41
  • This doesn't really have to do with checked vs. unchecked, though. It's really a question about polymorphism. – asteri Jan 22 '15 at 22:32
0

Every single class in java is a successor of java.lang.Object, but that doesn't mean that all of these classes are cast-able to each-other.

To a computer those two classes are completely different to each-other.

Caleb
  • 151
  • 2
  • 7