java.lang.Object
java.lang.Throwable
- Direct Known Subclasses:
- Error, Exception
- 对于RuntimeException,通常不需要我们去捕获,这类异常由java运行系统自动抛出并自动处理。
- 对于自定义的exception,流程如下:
- 1.自定义一个exception类
-
public class MyException extends Exception {
String message;
public MyException(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
}
- 2.在所定义的函数中抛出此exception
-
public class Register {
int num;
public Register(int num) throws MyException{
super();
this.num = num;
if(num<0){
throw new MyException("人数为负!");
}
}
}
- 3.调用此函数,截获此exception
-
public class Test {
public static void main(String[] args)
{
try{
Register stu = new Register(-1);
}catch(MyException e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
- 4.结果
- MyException: 人数为负!
at Register.<init>(Register.java:9)
at Test.main(Test.java:9)
人数为负!