重构 java 中的异常代码

Refactoring exception code in java

我正在编写应该为两个不同的事物抛出相同异常的代码,我不想将 throws Exception 与方法 getIsbnNumber() 一起使用。

有什么重构代码的方法吗?

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
}

的确,抛出一个异常,捕获它,然后再抛出它是没有意义的(除非有什么你想做的重新抛出它之前-这里似乎不是这种情况。

干脆扔一次不要接住:

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

我不认为这里有什么可以解决的。例如,在使用 IO 时,您会经常发现这种情况。这种代码看起来很眼熟?

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
   }
}

在 IO 的特定情况下,您可以使用更好、更安全的 Java 结构,即 try-with-resources :

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

如果您正在使用资源,请将它们设为 CloseableAutoCloseable 并使用它。否则,除了双重 try-catch 你别无选择。为我们提供更多详细信息以获得更好的答案。