java - 通用异常处理

标签 java exception

我发现下面的异常处理代码可以处理应用程序抛出的所有异常,包括运行时。

      public static void handleException(String strMethodName,
                    Exception ex) throws CustomException{
            String strMessage = "";
            try {
                throw ex;
            } 
            catch (NullPointerException npe){
                logger.log(pr, strMethodName, npe.getMessage());
                strMessage=ERR_02;
                throw new CustomException(strMessage);
            } 
            catch(IndexOutOfBoundsException iobe) {
                logger.logMethodException(strMethodName,iobe.getMessage());
                strMessage=ERR_03;
                throw new CustomException(strMessage);
            }
            ... So On
     }

以下是我认为的一些缺点:

  1. 为了确定异常的根本原因,我们需要始终检查消息字符串。
  2. 不区分异常类型

优点:

  1. 更少的代码。 (代码可以最小化)

您能否告诉我是否应该采用这种机制。

最佳答案

不确定您使用该代码的情况。

在您的方法中,您不会重新抛出可用于调试的异常对象

public static void handleException(String strMethodName,
                    Throwable th){
            String strMessage = "";
            try {
                throw th;
            } 
            catch (Throwable thr){
                logger.log(pr, strMethodName, npe.getMessage());
                //get the appropriate error code from a method
                strMessage=getErrorCode();
                throw new CustomException(strMessage, th); 
               //CustomException is of type RuntimeException
            }
     }

通过捕获并“抛出”Throwable 对象,您可以确保即使是错误也能得到正确处理。 [重要的是不要抑制 Throwable 对象]

关于java - 通用异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213063/

相关文章:

java - 设置 RGB 值以减少 PNG 图像中的调色板

java - 检查与直线和矩形的碰撞

C# System.InvalidCastException 异常

android - 多个数据报告实用程序可以报告同一个未捕获的异常吗?

java - 自定义标签无法正常工作

java - 如何将多模块项目分发为单个可运行的 jar 文件?

java - 查明类是否显式声明实现特定接口(interface)

python - Python 中是否有 raise foo, bar 的用例?

Java 控制台整体

c# - CLR 是否会同时处理符合 CLS 和不符合 CLS 的异常?