Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 770
sav0h Avatar asked Jan 17 '26 20:01

sav0h


1 Answers

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 { ... }
like image 78
Mohammed Aouf Zouag Avatar answered Jan 20 '26 09:01

Mohammed Aouf Zouag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!