我定义了一个自定义异常,如下所示:
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)。任何人都可以帮我在自定义异常中打印堆栈跟踪吗?
答案 0 :(得分: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();
}
}