sav0h
sav0h

Reputation: 391

One method call, multiple possible error conditions - how to manage this in Object Oriented Programming?

I am new to Java / OOP and I'm interested in learning about the standard approach(es) to this problem.

Let's say my Java program contains the following main method:

public static void main(String[] args) {
    String name = args[1];
    Person person = PersonHelper.getPerson(name);
}

Imagine that calling the getPerson method (with the help of other methods and classes defined in PersonHelper.java) does the following:

  1. Builds a url from a template to get data about "name" from a remote server, e.g. https://allofthepeople.com/name becomes https://allofthepeople.com/Alice
  2. Uses this url to read JSON formatted data about Alice from the server into a buffer
  3. Deserializes this data using a JSON parser into a Person object
  4. Returns the object

Now there are (at least) three exceptions which could be thrown during this routine:

  1. MalformedURLException (e.g. perhaps if I pass in binary data instead of a name)
  2. IOException (e.g. if /Alice does not exist)
  3. JSONParseException (e.g. if the server's response is not in JSON format)

Supposing that the method calling getPerson (main in this case) needs to be able to differentiate between these three exceptions, how should this be done? I don't see how the exception itself can be returned, since the assignment Person person = PersonHelper.getPerson(name) is expecting a Person object.

Upvotes: 3

Views: 77

Answers (1)

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17142

Proceed this way:

public static void main(String[] args) {
    String name = args[1];

    try {
        Person person = PersonHelper.getPerson(name);
    }
    catch(MalformedURLException e) {
        // Handle exception
    } 
    catch(IOException e) {
        // Handle exception
    } 
    catch(JSONParseException e) {
        // Handle exception
    } 
}

And change the getPerson method's signature so that it throws the 3 exceptions, let the main do the handling.

public static getPerson(String name) 
     throws MalformedURLException, IOException, JSONParseException { ... }

Upvotes: 5

Related Questions