Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print stack trace in custom exception?

Tags:

java

logging

I define a custom exception like so :

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);
    }
}

In the main program I use this exception like so :

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);
        }
    }

Now I don't know how to print stack trace when validatePath fail(means if statement become false) .Can anyone help me to print stack trace in custom exception?

like image 473
marzie Avatar asked Oct 19 '22 01:10

marzie


1 Answers

Why not just using 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();
    }
}
like image 122
Hong Duan Avatar answered Oct 21 '22 21:10

Hong Duan