You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java自定义RecordNotFoundException抛出报错,求问题排查

自定义异常抛出时编译错误排查

我尝试在Java中创建自定义异常,但抛出该异常时出现编译错误,已参考自定义异常教程实现。

自定义异常代码

package projectdemo.exception;

import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends Exception { 
    public RecordNotFoundException(String errorMessage) {
        super(errorMessage);
    }
}

抛出异常的服务类代码

package projectdemo.service;

import projectdemo.model.MasterUser;
import projectdemo.classes.Response;
import projectdemo.repository.Repository;
import projectdemo.exception.RecordNotFoundException; //已导入该类
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.http.ResponseEntity;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class MasterUserService {
    @Autowired
    private Repository repository;
    
    @Transactional(rollbackFor = Exception.class) 
    public ResponseEntity<Response<MasterUser>> method(Long id) { 

        MasterUser userExitsing = repository.findById(id).orElse(null);
        if(userExitsing == null) throw new RecordNotFoundException("User not found"); //此处报错
        
        
        Response<MasterUser> apiRes = new  Response<userExitsing );
        return new ResponseEntity<Response<MasterUser>>(apiRes, apiRes.status);
    }

}

错误截图

错误截图

问题原因及解决方案

核心问题

你的RecordNotFoundException继承了Exception(属于受检异常),Java语法要求:受检异常必须要么被try-catch块捕获处理,要么在方法签名上声明抛出该异常。而你的method方法既没有捕获该异常,也没有声明抛出,因此触发编译错误。

两种解决方法

  1. 在方法签名上声明抛出异常
    修改method方法的定义,添加throws RecordNotFoundException:
@Transactional(rollbackFor = Exception.class) 
public ResponseEntity<Response<MasterUser>> method(Long id) throws RecordNotFoundException { 
  1. 将自定义异常改为非受检异常
    修改自定义异常类,让它继承RuntimeException(非受检异常无需在方法签名声明):
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends RuntimeException { 
    public RecordNotFoundException(String errorMessage) {
        super(errorMessage);
    }
}

这种方式更适合Spring环境,因为Spring能通过@ResponseStatus注解自动处理HTTP状态码,无需额外的异常声明。

额外语法错误修复

服务类代码中还有一处语法错误:

Response<MasterUser> apiRes = new  Response<userExitsing );

应修正为:

Response<MasterUser> apiRes = new Response<>(userExitsing);

内容的提问来源于stack exchange,提问作者Hansen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:25:29