package com.niit.exception;class MyException extends Exception {
private int exceptnumber;
MyException(int a) {
exceptnumber = a;
}
public String toString() {
return "MyException[" + exceptnumber + "]";
}
}
public class ExceptionExample {
static void makeexcept(int a) throws MyException {
System.out.println("called makeexcept(" + a + ").");
if(a == 0) {
Throw new MyException(a);
}
System.out.println("exit without exception");
}
public static void main(String[] args) {
try {
makeexcept(5);
makeexcept(0);
} catch(MyException e) {
System.out.println("caught " + e);
}
}}
这段代码是书中的例子程序,可是在MyEclipse中却在 Throw new MyException(a); 这一行报错,按照MyEclipse修改为Object Throw = new MyException(a);但是结果却不一样了,变成了called makeexcept(5).
exit without exception
called makeexcept(0).
exit without exception。
按照程序的意思结果应该是
called makeexcept(5).
exit without exception
called makeexcept(0).
caught MyException[0]请知道的解释一下,谢谢
Throw new MyException(a);
}
改为
if(a == 0) {
throw new MyException(a);
}
throw中的t要小写,它是关键字
从main方法开始, makeexcept(5);会调用alled makeexcept(5),exit without exception.
makeexcept(0),调用alled makeexcept(0),然后捕获到异常执行caught MyException[0]