Reputation: 391
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:
Now there are (at least) three exceptions which could be thrown during this routine:
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
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