1. 人工抛出异常
- Java异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出,也可根据需要人工创建并抛出
- 首先要生成异常类对象,然后通过throw语句实现抛出操作(提交给Java运行环境)。
IOException e = new IOException();
throw e; - 可以抛出的异常必须是Throwable或其子类的实例。下面的语句在编译时将会产生语法错误:
- throw new String(“want to throw”);
2. 示例
static void test2(int i){
if(i == 0){
throw new ArithmeticException();
}
}
3. 创建用户自定义异常类
- 自定义异常:自己定义的异常类,通常情况下继承RuntimeException
- 自定义异常的作用:看见异常类的名字,就知道出现了什么问题
- 自定义异常通常都需要用throw关键字抛出
4. 示例:
public class UserNotExistException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UserNotExistException(){
}
public UserNotExistException(String msg){
super(msg);
}
}
public class TestUserNotExistException {
public static void main(String[] args){
String user = "Tom";
Object result = getUser(user);
}
public static Object getUser(String user){
List<String> users = Arrays.asList("aa","bb","cc");
if(users.contains(user)){
return new User();
}else{
throw new UserNotExistException("用户不存在");
}
}
}