} catch (Exception ex) {
ex.printStackTrace();
}
我捕获了一个异常 , 但怎么把错误信息转换字符串呢. 注意如下:
1)ex.toString() 这个取不到我要的错误信息(不如ex.printstacktrace()输出的全)
2)
StackTraceElement[] se = ex.getStackTrace();
for (int i = 0; i < se.length; i++) {
System.out.println(se[i].toString());
}//这个也是去不得错误信息(不如ex.printstacktrace()输出的全)

解决方案 »

  1.   

    用log4j 或者 
    public CustomException extends Exception{
    .......
    ....
    ..
    .
    }
      

  2.   

    没有很好的描述需求
    建议自定义一个总的Exceptionpublic abstract class GoodsException extends Exception{
    /**
     * 
     */
    private static final long serialVersionUID = 1L; public GoodsException(){
    super();
    } public GoodsException(String message){
    super(message);
    } public GoodsException(Throwable cause){
    super(cause);
    } public GoodsException(String message, Throwable cause){
    super(message, cause);
    }
    }
    在继承定义详细Exceptionpublic class DpulicationGoodsException extends GoodsException { /**
     * 
     */
    private static final long serialVersionUID = 1L; public DpulicationGoodsException(){
    super();
    } public DpulicationGoodsException(String message){
    super(message);
    } public DpulicationGoodsException(Throwable cause){
    super(cause);
    } public DpulicationGoodsException(String message, Throwable cause){
    super(message, cause);
    }
    }利用多态捕获总的catch(GoodsException e){
              err.println(e.getMessage());
           }
    什么信息都有了,O(∩_∩)O哈!,希望对你又帮助哈
      

  3.   

    public static void main(String[] args) {
    try {
    String str = "sss";
    Integer.valueOf(str);
    } catch (Exception ex) {
    //是否是少了这行
    System.out.println(ex.getLocalizedMessage());
    StackTraceElement[] se = ex.getStackTrace();
    for (int i = 0; i < se.length; i++) {
    System.out.println(se[i].toString());
    }
    }
      

  4.   

    我比较了NumberFormatException异常的
    ex.printStackTrace(); 

    StackTraceElement[] se = ex.getStackTrace(); 
    for (int i = 0; i < se.length; i++) { 
    System.out.println(se[i].toString()); 
    }
    2者差了一个 System.out.println(ex.getLocalizedMessage());
      

  5.   

    你可以看看java的源程序,Throwable类有具体的日志输出。
      

  6.   

    public void printStackTrace(PrintStream s)
    public void printStackTrace(PrintWriter s) 你可以自己指定输出流!
      

  7.   

    e.printStackTrace(new PrintWriter())
      

  8.   

    String s = null;
    try {
    throw new Exception("An exception thrown!");
    } catch (Exception e) {
    Writer w = new StringWriter();
    e.printStackTrace(new PrintWriter(w));
    s = w.toString();
    }
    System.out.println(s);