自定义异常时exception is never thrown in the corresponding try block和unhandled exception

在这里插入图片描述在这里插入图片描述

自己的异常:

public class UserNotExistsException extends Exception{
    private static final long serialVersionUID = 1L;

    public UserNotExistsException()
    {
        super("user.not.exists", null);
    }
}

调用:

  @Override
    public User selectUserByLoginName(String userName,String password) {

            if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password))
            {//校验空
                //信息写入到用户操作日志中
                //    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
                throw new UserNotExistsException();
            }
          if(userMapper.selectUserByLoginName(userName,password)==null)
          {
              throw new UserPasswordNotMatchException();
        }
        return userMapper.selectUserByLoginName(userName,password);
    }

另一处调用service的地方:

  User user = null;
try {
    user = userService.selectUserByLoginName(username, password);
}

        catch (UserNotExistsException e)
        {
            throw new UnknownAccountException(e.getMessage(),e);
        }
        ...

全局处理:

    @ExceptionHandler(UserNotExistsException.class)
    @ResponseBody
    public ResponseResult handUserException()
    {
        return ResponseResult.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR,ResponseEnum.USERNAME_OR_PASSWORD_ERROR.getDesc());
    }

解决:应该改成extends RuntimeException
注意, RuntimeException是Exception的子类,与IOEXCEPTION同级,java将派生于 RuntimeException的所有异常称为未检查异常,所有其他的异常为已检查异常, RuntimeException这个名字容易让人混淆,实际上现在讨论的所有错误都发生在运行时
 java.lang.Throwable 1.0
 ·Throwable()构造一个新的Throwable对象,这个对象没有详细的描述信息。
 ·Throwable(String message) 构造一个新的throwable对象,这个对象带有特定的详细描述信息。习惯上,所有派生的异常类都支持一个默认的构造器和一个带有详细描述信息的构造器。
 ·String getMessage() 获得Throwable对象的详细描述信息。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值