Talha
Talha

Reputation: 12719

Custom exception handling error

I have custom exception which extends JSONException and i want my method to throw this exception rather than using try catch in my method.

When i use my exception, IDE still warning me to handle JSON exception.

Exception

public class NoBorderException extends JSONException {
    public NoBorderException(String s) {
        super(s);
    }

    public  String getMessage(){
        return  super.getMessage();
    } 
}

Method - unhandled JSON exception

    private void loadNeighboringCountries(String data) throws NoBorderException {
            final JSONArray arrBorders = new JSONArray(data);
            System.out.print(arrBorders.get(0));

Method - No problem

private void loadNeighboringCountries(String data) throws JSONException{
        final JSONArray arrBorders = new JSONArray(data);
        System.out.print(arrBorders.get(0));

Thanks,

Upvotes: 0

Views: 375

Answers (1)

Saran Tunyasuvunakool
Saran Tunyasuvunakool

Reputation: 1109

The JSONArray constructor (and indeed the get method) throws a JSONException. Your method is only declared to throw a NoBorderException and not the superclass, which means that JSONException remains unhandled.

In short, the declaration throws NoBorderException covers any subclass of NoBorderException, but not its superclass JSONException.

If you want this method to throw your custom exception type then you will need to do something like this:

try {
    final JSONArray arrBorders = new JSONArray(data);
    System.out.print(arrBorders.get(0));
}
catch (JSONArray e) {
    throw new NoBorderException(e.getMessage());
}

Upvotes: 3

Related Questions