2015-09-27 105 views
2

我定义了一个自定义异常,像这样:如何在自定义异常中打印堆栈跟踪?

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失败(意味着如果语句变为false)。任何人都可以帮助我在自定义异常中打印堆栈跟踪?

+0

'ValidationException e = new ValidationException(); logger.error(“Exception:{}”,e);' - 这意味着什么? – immibis

+0

@ immibis yes.but当我在ValidationException类中定义这个陈述给我一个错误。在readFile()方法中,如果validate Path是false,我想停止运行,然后用logback在文件中打印栈tarce – marzie

+0

为什么要登录异常构造函数?也许你的意思是'logger.error(“Error”,this)'? –

回答

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(); 
    } 
} 
+0

我在哪里使用try块?在readFile()方法中?我是java中的新成员。 – marzie

+0

请参阅您的readFile()中的编辑。 –