如何自定义写自定义异常类

fxpopboy 2008-09-12 10:21:32
要在异常类里面捕获到错误信息、错误代码、函数名、文件名,希望高手给予答复
...全文
343 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
landyshouguo 2008-09-15
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 Landor2004 的回复:]
很简单,给你一个简单的例子
1 定义异常类

Java codepublic class TestException extends Exception {
private String e;
public TestException(String e){
this.e = e;
}
public String toString(){
return "抛出异常"+e;
}
}


2 测试类

Java codepublic class Test {
public static void main(String[] args) {
String yourString="xxxxx";//这里是…
[/Quote]jf
dsgdsg 2008-09-15
  • 打赏
  • 举报
回复
楼主结贴啊!
ZangXT 2008-09-12
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 fxpopboy 的回复:]
格式化异常栈是要用,但我在Action中写了
Action里面
try{
.......
}catch(TestException e){//出错了
..........
}
Action类里面
public static void Action() throws TestException{
throw new TestException("......“);
}
却在我表明的出错了地方放报错了

[/Quote]
这个好像本来就不确定。
fxpopboy 2008-09-12
  • 打赏
  • 举报
回复
格式化异常栈是要用,但我在Action中写了
Action里面
try{
.......
}catch(TestException e){//出错了
..........
}
Action类里面
public static void Action() throws TestException{
throw new TestException("......“);
}
却在我表明的出错了地方放报错了
funcreal 2008-09-12
  • 打赏
  • 举报
回复
楼主是否要自己来格式化异常栈内容呢?如果是的话请参考一下代码。可能与你说的思路不同。

Throwable t = 你捕获到的异常。
while(t!=null){
out.print("<font color='red'>");
out.print(t.getClass().getName()+ ":"+t.getMessage()+"<br/>");
out.print("</font>");
StackTraceElement[] elements = t.getStackTrace();
for(int i=0;i<elements.length;i++){
StackTraceElement e = elements[i];
out.print("   "+e.getClassName()+"#");
out.print(e.getMethodName()+"");
out.print("(line:"+e.getLineNumber()+")");
out.print("<br/>");
}
t = t.getCause();
}
Landor2004 2008-09-12
  • 打赏
  • 举报
回复
很简单,给你一个简单的例子
1 定义异常类
public class TestException extends Exception {
private String e;
public TestException(String e){
this.e = e;
}
public String toString(){
return "抛出异常"+e;
}
}

2 测试类
public class Test {
public static void main(String[] args) {
String yourString="xxxxx";//这里是你说的错误信息、错误代码、函数名、文件名等等信息,要自己写的
try{
test(yourString);//执行普通函数
}catch(TestException e){
System.out.println(e);
}
}
//普通函数,在此处跑出自定义的异常
public static void test(String yourString) throws TestException{
throw new TestException(yourString);
}
}
fxpopboy 2008-09-12
  • 打赏
  • 举报
回复
主要是不会写,还要麻烦大家帮忙写下,比较急
绿绦 2008-09-12
  • 打赏
  • 举报
回复
把错误信息 组合成一个字符串作为构件一个异常( 在NEW的时候给构造方法)的参数就可以了
dsgdsg 2008-09-12
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 Landor2004 的回复:]
很简单,给你一个简单的例子
1 定义异常类
Java codepublicclassTestExceptionextendsException {privateString e;publicTestException(String e){this.e=e;
}publicString toString(){return"抛出异常"+e;
}
}
2 测试类
Java codepublicclassTest {publicstaticvoidmain(String[] args) {
String yourString="xxxxx";//这里是你说的错误信息、错误代码、函数名、文件名等等信息,要自己写的try{

[/Quote]最简单的!
shendiaoke 2008-09-12
  • 打赏
  • 举报
回复
上面几位说的很好 楼主照做就ok了

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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