【问题标题】:how to create a utility method which has checked exception?如何创建一个检查异常的实用方法?
【发布时间】:2014-09-19 21:37:33
【问题描述】:

我必须使用以下代码在我的 struts 2 应用程序操作类方法中设置 private InputStream responseMsg

responseMsg = new ByteArrayInputStream(message.getBytes("UTF-8"));

在这种情况下,我必须处理 UnsupportedEncodingException 已检查异常。如果我在所有方法中添加throws UnsupportedEncodingException,我想在这么多操作方法中分配InputStream,这意味着代码看起来很乱。所以我决定在实用程序类中创建实用程序方法

public class Utilities {

    public InputStream responseMessage(String message) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(message.getBytes("UTF-8"));
    }
}

从我的动作类调用

responseMsg = new Utilities().responseMessage(message);

在这种情况下,还要编译时间错误来处理动作方法中的UnsupportedEncodingException,帮助我为我的所有动作类方法创建实用程序方法。

【问题讨论】:

  • 只处理异常......不明白你在问什么。
  • 你用 Utility 方法保存了什么?它仍然会抛出 UnsupportedEncodingException,并且该方法的调用者必须处理它或声明他们抛出它。

标签: java struts2 utilities


【解决方案1】:

如果您专门谈论"UTF-8",推荐的方法是如果必须按照规范工作的东西不工作,则抛出Error。例如

public InputStream responseMessage(String message) {
  try {
    return new ByteArrayInputStream(message.getBytes("UTF-8"));
  } catch(UnsupportedEncodingException ex) {
    throw new AssertionError("Every JVM must support UTF-8", ex);
  }
}

由于 Java 7 live 对于这种特定情况要容易得多:

public InputStream responseMessage(String message) {
  return new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
}

如果涉及到任意字符集,您应该处理可能的异常,这没什么大不了的,因为使用返回的InputStream 的代码无论如何都必须处理声明的IOExceptions,而UnsupportedEncodingException 是一个IOException 的子类。因此IOException 所需的catchthrows 子句将覆盖UnsupportedEncodingException

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多