0

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,

1 Answer 1

3

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()); } 
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your reply, i know that when i surround it it wors, but i havent understood what is the problem with this ? MyException extends JsonException so, i assume that, it should work ??
As I mentioned in the post: the declaration throws NoBorderException covers any subclass of NoBorderException, but not its superclass JSONException.
Ok thanks, so there are no same hierarcy between JSONexception -> Exception and NoBorderException->JSONexception.
There is a hierarchy, but you've got it the wrong way round. You need to declare the most general exception class that your method throws (or, indeed, declare multiple throws). In this case JSONException is more general than NoBorderException, since it is the superclass.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.