本帖最后由 位丹丹 于 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>
复制代码 |