Javaexception处理 – 捕获超类exception

我有一个关于在Web应用程序中处理exception的问题。 我经常听到抓住超类exception是一个坏主意。

我经常编写代码来捕获struts action / java servlet类中的所有exception。

try { // call business facade // business facade calls DAO // any exception from DAO bubbles up } catch (Exception e) { log.error("error", e); } 

如果我们不捕获超类Exception。 我们如何处理任何意外的运行时错误并适当地记录它们

您可以为项目设置DefaultUncaughtExceptionHandler来处理未捕获的exception。 例如,这是我在其中一个项目中的一段代码:

 private static void setDefaultUncaughtExceptionHandler() { try { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { logger.error("Uncaught Exception detected in thread {}", t, e); } }); } catch (SecurityException e) { logger.error("Could not set the Default Uncaught Exception Handler", e); } } 

在Web应用程序中,以及在您发布的代码段中,您如何处理根Exception ? 它看起来像你抓住它,记录它,继续前进。

在webapp中99%的情况下,最好允许Exception冒泡到web.xml中配置的

如果你在“调用业务外观”时发现一个未知错误,那么你似乎不太可能在你的应用程序中使用其余的逻辑来保持卡车运输。

添加多个catch块并将Exception catch作为最后一个。

 try { // call business facade // business facade calls DAO // any exception from DAO bubbles up } catch(SuperClassException se) { //Do what you want to do when this exception happens. }catch (Exception e) { log.error("error", e); } 

使用Struts,您可以配置一个exception处理程序来捕获和处理从Action抛出的任何exception。 至少从Struts 1.2开始,该function已经存在。 您的Action类不需要任何try-catch块,除非您需要执行某些特定操作来处理特定exception。

try里面的代码主要指定并标记你可以捕获的已检查exception。 此外,查看内部代码尝试您可以直接针对失败案例的情况,并因此可以添加未经检查/运行时exception捕获块。