Java 一个异常方法,记录并抛出异常,异常作为参数出现

Java 一个异常方法,记录并抛出异常,异常作为参数出现,java,exception-handling,Java,Exception Handling,我有一个Util类,在这个类中,我试图实现一个简单的方法,它记录即将到来的消息并抛出发送的异常。原因很简单,我没能做到 我目前的方法是这样的 public static void handleException( Exception exception, String errorMessage ) { LOGGER.error( errorMessage + "\n " + exception.getMessage() ); throw new IllegalArgumen

我有一个Util类,在这个类中,我试图实现一个简单的方法,它记录即将到来的消息并抛出发送的异常。原因很简单,我没能做到

我目前的方法是这样的

 public static void handleException( Exception exception, String errorMessage )
  {
    LOGGER.error( errorMessage + "\n " + exception.getMessage() );
    throw new IllegalArgumentException( errorMessage + "\n " + aException.getMessage() );
  }
但是,我不仅想要IllegalArgumentException,还想要异常的类型,它作为参数发送(也称为异常)


哪种方法是最好的实现方法?

您可以向方法中添加一个类型参数,然后重新显示原始异常:

public static <T extends Exception> void handleException(
    T exception,
    String errorMessage
    ) throws T
{
    LOGGER.error( errorMessage + "\n " + exception.getMessage() );
    throw exception;
}

或者类似的东西…

您可以向方法中添加一个类型参数,然后重新显示原始异常:

public static <T extends Exception> void handleException(
    T exception,
    String errorMessage
    ) throws T
{
    LOGGER.error( errorMessage + "\n " + exception.getMessage() );
    throw exception;
}

或者类似的东西…

你为什么不重新描述一下你一开始遇到的异常呢

抛出异常

如果这不符合您的需求,您可以尝试通过从异常中获取类并使用反射来创建新实例(可能会出错,因为可能存在不同的构造函数)


希望它能有所帮助

为什么不重新显示一开始遇到的异常呢

抛出异常

如果这不符合您的需求,您可以尝试通过从异常中获取类并使用反射来创建新实例(可能会出错,因为可能存在不同的构造函数)


希望它能有所帮助

为什么要创建一个新的异常,而不是简单地将已经得到的异常作为参数抛出?@ArcticLord我只想将异常处理集中在一个Util类中。我不喜欢在代码中到处抛出异常。为什么要创建一个新的异常,而不是简单地抛出已经作为参数得到的异常?@ArcticLord我只想将异常处理集中在一个Util类中。我不喜欢在代码中到处抛出异常。工作起来很有魅力。谢谢,很有魅力。谢谢。我只想把异常处理集中在一个地方。在一个方法中,我发现它更符合逻辑,而不是在代码中编写日志和抛出异常。我只想将异常处理集中在一个地方。在一个方法中,我发现它更符合逻辑,而不是编写日志并在代码中抛出异常。
public static <T extends Exception> void handleException(
    T exception,
    String errorMessage
    ) throws T
{
    final String newMessage = errorMessage + "\n " + exception.getMessage();
    LOGGER.error(newMessage);
    T newException = exception;
    try {
        newException = (T)exception.getClass()
                                .getConstructor(new Class[] { String.class, Exception.class })
                                .newInstance(new Object[] { newMessage, exception});
    } catch (Exception) {
    }
    throw newException;
}