JAVA中的异常的后续
一、抛出异常
throws语句
throws用在声明方法是,表示该方法可能要抛出异常,调用者必须作出处理,捕获或继续抛出异常。
public class ThrowsExceptionTest {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("请输入字符串");
String str = scn.next();
int num = Integet.parseInt(str);
System.out.println(num);
}
}
二、自定义异常类
public class RegisterException extends Exception {
ststic final long serialVersionUID = 34897193246939L
public RegisterException() {
}
public RegisterException(String str) {
super(str);
}
}
public class UserRegistTest {
public void regist(int num) throws RegisterException {
if( num < 0 ) {
throw new RegisterException("注册编号为负值,不合理");
}
else {
System.out.println("注册编号为" + num);
}
}
public static void main(String[] args) {
UserRegisteTest t = new UserRegisteTest();
Scanner scn = new Scanner(System.in);
System.out.println("请输入要注册的用户的编号为:");
int ID = scn.nextInt();
try {
t.regist(ID);
}catch(RegisterException e) {
e.printStackTrace();
}
}
}