如何检查Exception中的变量类型?

时间:2015-04-25 09:02:21

标签: java syntax-error

我在程序中创建了自己的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

1 个答案:

答案 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");
    }
}