如何 把 printStackTrace()转换成字符串

killvs 2009-07-02 06:02:52
} 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()输出的全)
...全文
442 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
冰思雨 2009-07-03
  • 打赏
  • 举报
回复
被楼上的抢先了。
顶一下吧。
Dan1980 2009-07-03
  • 打赏
  • 举报
回复
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);
sinpinle 2009-07-03
  • 打赏
  • 举报
回复
e.printStackTrace(new PrintWriter())
老紫竹 2009-07-03
  • 打赏
  • 举报
回复
public void printStackTrace(PrintStream s)
public void printStackTrace(PrintWriter s)

你可以自己指定输出流!
yztommyhc 2009-07-02
  • 打赏
  • 举报
回复
你可以看看java的源程序,Throwable类有具体的日志输出。
yztommyhc 2009-07-02
  • 打赏
  • 举报
回复
我比较了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());
yztommyhc 2009-07-02
  • 打赏
  • 举报
回复
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());
}
}
callwww 2009-07-02
  • 打赏
  • 举报
回复
没有很好的描述需求
建议自定义一个总的Exception

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


在继承定义详细Exception

public 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哈!,希望对你又帮助哈
一头头 2009-07-02
  • 打赏
  • 举报
回复
用log4j 或者
public CustomException extends Exception{
.......
....
..
.
}
killvs 2009-07-02
  • 打赏
  • 举报
回复
转换成字符串的目的是我要写道数据库里面

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧