Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何创建已检查异常的实用程序方法?_Java_Struts2_Utilities - Fatal编程技术网

Java 如何创建已检查异常的实用程序方法?

Java 如何创建已检查异常的实用程序方法?,java,struts2,utilities,Java,Struts2,Utilities,我必须使用以下代码在struts 2应用程序操作类方法中设置私有InputStream responseMsg responseMsg = new ByteArrayInputStream(message.getBytes("UTF-8")); 在这种情况下,我必须处理UnsupportedEncodingExceptionchecked异常。如果我在所有方法中添加了抛出不支持的codingexception,那么我想在这么多操作方法中分配InputStream,这意味着代码看起来很凌乱。所以

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

responseMsg = new ByteArrayInputStream(message.getBytes("UTF-8"));
在这种情况下,我必须处理
UnsupportedEncodingException
checked异常。如果我在所有方法中添加了
抛出不支持的codingexception
,那么我想在这么多操作方法中分配
InputStream
,这意味着代码看起来很凌乱。所以我决定在一个实用类中创建实用方法

public class Utilities {

    public InputStream responseMessage(String message) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(message.getBytes("UTF-8"));
    }
}
从我的action类调用

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

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

如果您专门谈论
“UTF-8”
,建议的方法是,如果某些必须按规范工作的东西不能正常工作,则抛出一个
错误。例如

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
的代码将不得不处理声明的
IOException
s,并且
unsupportedcodingexception
IOException
的子类。因此,对于
IOException
所需的
catch
throws
子句将涵盖
UnsupportedEncodingException

只需处理异常。。。。不明白你在问什么。你用效用法节省了什么?它仍然会抛出UnsupportedEncodingException,该方法的调用方必须处理它或声明抛出它。