A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 位雪 中级黑马   /  2012-8-23 13:56  /  1605 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 位丹丹 于 2012-8-23 13:58 编辑

自定义异常信息时,为什么不可以抛出父类异常Exception,而必须抛出自定义异常?自定义异常不是继承Exception吗?
  1. class FuShuException extends Exception{
  2. private String msg;
  3. private int value;
  4. FuShuException()
  5. {
  6. super();
  7. }
  8. FuShuException(String msg,int value)
  9. {
  10. super(msg);
  11. this.msg = msg;
  12. }
  13. public int getValue()
  14. {
  15. return value;
  16. }
  17. }
  18. class Demo2
  19. {
  20. int div(int a,int b) throws FuShuException<FONT color=red>//此处疑问,若抛出Exception,出现Exception in thread "main" java.lang.Error: 无法解析的编译问题:未处理的异常类型Exception
  21. </FONT>{
  22. if(b<0)
  23. throw new FuShuException("出现除数是负数的情况------",b);//手动通过throw抛出自定义异常
  24. return a/b;
  25. }
  26. }
  27. public class ExceptionDemo2 {

  28. public static void main(String[] args) {

  29. Demo2 d = new Demo2();

  30. try
  31. {
  32. int x = d.div(4, -1);

  33. System.out.println("x = "+x);
  34. }
  35. catch (FuShuException e)
  36. {
  37. System.out.println(e.toString());//day09.FuShuException
  38. System.out.println("除数出现负数");
  39. }


  40. System.out.println("over");

  41. }

  42. }
  43. </P>
复制代码

1 个回复

倒序浏览
public class ExceptionDemo2 {
public static void main(String[] args) {
Demo2 d = new Demo2();
try
{
int x = d.div(4, -1);
System.out.println("x = "+x);
}
catch (FuShuException e)
{
System.out.println(e.toString());//day09.FuShuException
System.out.println("除数出现负数");
}
catch(Exception e){}//这个是我给你添加上的。
System.out.println("over");
}
}
你的源码不改时,你int x = d.div(4, -1);语句会抛出1个自定义异常那就只要1个catch块。
当你把那句话给成Exception时,那就时2个异常,一个自定义和一个Exception异常。那就要有2个catch块,不然你主函数就要向外抛异常。

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马