我在程序中创建了自己的Exception,但它显示错误
class InvalidTypeException extends Exception {
InvalidTypeException(String s) {
super(s);
}
}
public class CustomException1 {
static void valid(int a) throws InvalidTypeException {
if (a instanceof Integer) throw new InvalidTypeException("Valid");
else System.out.println("Invalid");
}
public static void main(String args[]) {
try {
valid(12);
} catch (Exception e) {
System.out.println(e);
}
}
}
编译错误是:
src\CustomException1.java:11: error: unexpected type
if(a instanceof Integer )
^
required: reference
found: int
1 error
答案 0 :(得分:4)
您无法在原始类型上使用instanceof
运算符,例如a
当前已定义。您可以将参数类型定义为Object
:
static void valid(Object o) throws InvalidTypeException {
if (o instanceof Integer) {
throw new InvalidTypeException("Valid");
} else {
System.out.println("Invalid");
}
}