java - Throwing and catching exceptions correctly -


so have 1 question. lets have classes: main, info, cats, food

now, lets in main create new object info. in info object saving list of cats have been created. cats being created , stored in info class , food being created , stored in cats class. lets say, in main class, want specific food object, stored in cats class. so, in order following:

info.getfood(name). in info's getfood method cats.getfood(name). finally, in cats class have method getfood, in try find food object field "name". if unable find such element, throw nosuchelement exception rather return object. here question:

if throw exception in cats class getfood method, should catch exception in main class (where our interface is), in info class (which our system class) or in both of them?

generally speaking, inside method, if can exception being thrown (log error, show error message, make different decision in code, etc), should catch it. otherwise, throw calling method.

as many other coding practices, boils down , team agree on.

a concrete example isn't related code, show how decision process can made. assume following code:

public myconfiguration loadconfiguration () throws configurationexception {     myconfiguration config = null;      try {         readconfigurationfromfile ();          // parse configuration string      } catch (ioexception ioex) {         throw new configurationexception (ioex);     }      return config; }  private string readconfigurationfromfile () throws ioexception {     string configuration = "";      // read file on disk, append data string.      return configuration; } 

in readconfigurationfromfile (), if exception occurs while reading file, you'll ioexception. @ point in code, there's no real action can take, since method reads configuration file, appends data string, returns it.

in loadconfiguration (), can surround call readconfigurationfromfile () try/catch, , throw more generic exception (configurationexception). again, @ point, there's nothing can exception, except wrap in new exception adds more context information original exception thrown.

now assume there's 2 flavors of software: gui version, , command-line version. if running gui flavor, method calling loadconfiguration decide show error message user whenever configurationexception being thrown, user knows happened. if running command-line version, maybe more logical add entry error log exception caught.


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -