gpt4 book ai didi

java - 如何为 servlet 的 init() 方法抛出异常

转载 作者:搜寻专家 更新时间:2023-10-31 19:28:52 24 4
gpt4 key购买 nike

好吧,我先展示一下我的代码:

@Override
public void init() throws ServletException {
super.init();

try {
securityController = SecurityControllerFactory.getInstance().create();
} catch (Exception e) {
System.err.println("Error creating security controller; " + e.getMessage());
}

// max allowed uploaded uploadedFile size is 10 MB
maxFileSize = getBytes(10);
maxMemSize = getBytes(2);
}

如您所见,编译器强制我使用 try/catch 来实例化 SecurityController。然而,就我而言,我认为如果无法实例化安全 Controller ,它应该停止实例化 Servlet 并通常抛出异常。对此有何建议/解释?

最佳答案

仔细阅读the javadoc of init() method :

init

public void init() throws ServletException

...

Throws:

ServletException - if an exception occurs that interrupts the servlet's normal operation

看那里,您应该将其作为 ServletException 重新抛出。符合 Servlet API specification 的第 2.3.2.1 章, servlet 将不会被放置在服务中:

2.3.2.1 Error Conditions on Initialization

During initialization, the servlet instance can throw an UnavailableException or a ServletException. In this case, the servlet must not be placed into active service and must be released by the servlet container. The destroy method is not called as it is considered unsuccessful initialization.

...

因此,只需按照文档中的说明进行操作(这是正常过程,顺便说一句,作为 Java 初学者,您应该很好地理解/意识到这一点):

@Override
public void init() throws ServletException {
try {
securityController = SecurityControllerFactory.getInstance().create();
} catch (Exception e) {
throw new ServletException("Error creating security controller", e);
}

maxFileSize = getBytes(10);
maxMemSize = getBytes(2);
}

请注意,我删除了不必要的 super.init() 调用。 javadoc 没有告诉任何地方您需要为 init() 执行此操作,仅针对 init(ServletConfig)


与具体问题无关,在 Exception 上使用过于通用的 catch 被认为是不好的做法。您当然不希望在 Exception 上使用过于通用的 catch 来覆盖 RuntimeException,因为这可能会无意中隐藏程序员的错误/错误。

您应该尝试在您的catch 中尽可能具体,尝试尽可能具体地捕获在这些方法的throws 中声明的异常。例如:

    try {
securityController = SecurityControllerFactory.getInstance().create();
} catch (SecurityControllerCreationException e) {
throw new ServletException("Error creating security controller", e);
}

另一个原因也可能是所讨论的方法设计得很糟糕,以至于它们自己被声明为 throws Exception。您也应该依次修复该部分。

关于java - 如何为 servlet 的 init() 方法抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16290614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com