Refactoring exception code in java

I am working on code that should throw the same exception for two different things, and I don’t want to use throws Exception with the method getIsbnNumber().

Is there any way of refactoring the code?

public void getIsbnNumber()
{
  try
  {
     value = new URN("urn:isbn:12345");
     if (value.getSecondElement() != "isbn")
     {
         //throws the urn same exception
     }
  }
  catch(URNException exception)
  {
      //throws the urn same exception
  }
  return value.getThirdElement(); // return 12345
}

Answer

I don’t think there is anything to fix here. This is something you can find a lot when working with IO, for example. This kind of code looks familiar ?

BufferedWriter bw = null;
try {
   bw = openWriter();
   doStuff();
} catch (IOException e) {
   handleError();
} finally {
   try {
       if (bw != null) bw.close();
   } catch (IOException e) { 
       // do nothing, or print stacktrace
   }
}

In the particular case of IO, you can use a nicer, and safer Java construct, which is the try-with-resources :

// this will close bw no matter what
try (BufferedWriter bw = openWriter()) {
   doStuff();
} catch (IOException e) {
   handleError();
}

If you are working with resources, make them Closeable or AutoCloseable and use this. Otherwise, you have no other option than the double try-catch. Give us more details for getting better answers.

Leave a Reply

Your email address will not be published. Required fields are marked *