如何在自定义异常中打印堆栈跟踪?

5

我定义一个自定义的异常,如下所示:

package source.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ValidationException extends Exception
{
    private static final Logger logger = LoggerFactory.getLogger("source.exception.ValidationException");

    public ValidationException(String message)
    {
        super(message);
        ValidationException e = new ValidationException();
        logger.error("Exception : {}" , e);
    }
}

在主程序中,我会这样使用这个异常:
public void readFile(String path) throws ValidationException
    {
        logger.debug("Input file path = {}" , path);
        try
        {
            if(validatePath(path))
            {
                mathExpressionReader = new BufferedReader(new FileReader(path));
            }
            else
            {
                throw new ValidationException("Your file dose not exist!");
            }
        }
        catch(Exception ex)
        {
            logger.error("Exception {} has occurred" , ex);
        }
    }

现在我不知道如何在validatePath失败时打印堆栈跟踪(意思是if语句变为false)。有人能帮我在自定义异常中打印堆栈跟踪吗?


ValidationException e = new ValidationException(); logger.error("Exception : {}" , e); 这是什么意思? - user253751
@immibis 是的。但是当我在 ValidationException 类中定义这个语句时,会出现错误。在 readFile() 方法中,如果 validate Path 为 false,我想停止运行,然后在文件中使用 logback 打印堆栈跟踪。 - marzie
你为什么要在异常构造函数里面记录日志?也许你的意思是 logger.error("Error", this) - George Simms
@George Simms 在readFile()方法中,我想通过定义自定义异常并在方法体中抛出来停止程序运行,然后使用logback打印堆栈跟踪,但我不知道如何实现? - marzie
1个回答

3
为什么不直接使用e.printStackTrace()
public class ValidationException extends Exception
{
    public ValidationException(String message)
    {
        super(message);
    }
}

public void readFile(String path) throws ValidationException
{
    logger.debug("Input file path = {}" , path);
    try
    {
        if(validatePath(path))
        {
            mathExpressionReader = new BufferedReader(new FileReader(path));
        }
        else
        {
            throw new ValidationException("Your file dose not exist!");
        }
    } catch (ValidationException e) {
        // This will print the stack trace.
        e.printStackTrace();
    }
}

我应该在哪里使用try块?在readFile()方法中吗?我是Java的新手。 - marzie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接