黑马程序员技术交流社区
标题: 自定义异常信息 [打印本页]
作者: 位雪 时间: 2012-8-23 13:56
标题: 自定义异常信息
本帖最后由 位丹丹 于 2012-8-23 13:58 编辑
自定义异常信息时,为什么不可以抛出父类异常Exception,而必须抛出自定义异常?自定义异常不是继承Exception吗?
- class FuShuException extends Exception{
- private String msg;
- private int value;
- FuShuException()
- {
- super();
- }
- FuShuException(String msg,int value)
- {
- super(msg);
- this.msg = msg;
- }
- public int getValue()
- {
- return value;
- }
- }
- class Demo2
- {
- int div(int a,int b) throws FuShuException<FONT color=red>//此处疑问,若抛出Exception,出现Exception in thread "main" java.lang.Error: 无法解析的编译问题:未处理的异常类型Exception
- </FONT>{
- if(b<0)
- throw new FuShuException("出现除数是负数的情况------",b);//手动通过throw抛出自定义异常
- return a/b;
- }
- }
- 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("除数出现负数");
- }
- System.out.println("over");
- }
- }
- </P>
复制代码
作者: 刘源 时间: 2012-8-23 14:25
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块,不然你主函数就要向外抛异常。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |