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