本帖最后由 LuckyQS 于 2014-1-18 14:59 编辑
package com.sun.java.day03;
class NegativeNumberException extends Exception{
private int value;
NegativeNumberException(String message,int value){
super(message);
this.value = value;
}
public int getValue(){
return value;
}
}
class Demo1{
int div(int a,int b)throws NegativeNumberException{
if(b<0)
throw new NegativeNumberException("出现了除数是负数的情况",b);
return a/b;
}
}
public class UserdefinedException {
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo1 d = new Demo1();
try {
System.out.println(d.div(4, 1));
} catch (NegativeNumberException e) {
System.out.println(e.toString());
System.out.println("错误的负数是:"+e.getValue());
}
}
}
为什么我自定义的异常会出现下面的问题呢?
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No exception of type NegativeNumberException can be thrown; an exception type must be a subclass of Throwable
at com.sun.java.day03.UserdefinedException.main(UserdefinedException.java:29) |