如何构建异常
%
-
直接用空构造
-
用String的构造
可以按照return 语句去理解,只是调用者是用try catch去获得返回值,所以catch要定义一个Exceptionq去接收throw的语句
throw new NullPointerException("t=null");
throw new NullPointerException();
如何自定义异常
%
继承Exception即可
//: exceptions/FullConstructors.java
package exceptions; /* Added by Eclipse.py */
//自定义异常
class MyException extends Exception {
public MyException() {}
//使用String构造
public MyException(String msg) { super(msg); }
}//自定义异常结束
public class FullConstructors {
public static void f() throws MyException {
System.out.println("Throwing MyException from f()");
throw new MyException();
}
public static void g() throws MyException {
System.out.println("Throwing MyException from g()");
throw new MyException("Originated in g()");
}
public static void main(String[] args) {
try {
f();
} catch(MyException e) {
e.printStackTrace(System.out);
}
try {
g();
} catch(MyException e) {
e.printStackTrace(System.out);//打印错误stack,原本是输出到System.eer流上
}
}
} /* Output:
Throwing MyException from f()
MyException
at FullConstructors.f(FullConstructors.java:11)
at FullConstructors.main(FullConstructors.java:19)
Throwing MyException from g()
MyException: Originated in g()
at FullConstructors.g(FullConstructors.java:15)
at FullConstructors.main(FullConstructors.java:24)
*///:~
什么是异常的说明
-
如果说明的比抛出的多会怎么样?
-
如果抛出的比说明的多会怎么样?
%
异常说明的形式,必须这样写,不能省略
void fun() throws One, Two, Three{//...
如果代码中只抛出了One,没影响
若果代码多抛出了一个Four,编译不通过