1,这里指的异常是程序员自定义的异常,比如StudentIsNullException,而不是自带的异常,比如ClassNotFoundException等;
2,自定义一个异常:比如下图,这样若firstname没有初始化,则执行sayHello()方法则会报异常:SpittleIsNullException
@Component //添加为Spring Bean
public class Spittle {
public String firstname;
public String lastname;
public String username;
public String password;
public void sayHello(){
if(this.firstname == null){
throw new SpittleIsNullException();
}
else System.out.println("你好,我的名字是"+this.firstname);
}}
3,实现一个继承自RunTimeException的SpittleIsNullException类,且加上注解:
@Component //添加为Spring bean
/*将异常映射为415(UNSUPPORTED_MEDIA_TYPE对应的码值就是415)*/
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE,
reason = "参数是空")
public class SpittleIsNullE