在Java8中以可选方式抛出自定义异常

时间:2018-11-11 14:50:27

标签: java java-8 optional

我有这段代码要在找不到资源的地方抛出异常

Menu menu = menuService.findById(addMenuAmount.getMenuId())
                    .orElseThrow(com.tdk.web.exception.ResourceNotFoundException(“menu "  + 
                            addMenuAmount.getMenuId() + " not found "));

但是出现编译错误:

com.tdk.web.exception cannot be resolved to a type

1 个答案:

答案 0 :(得分:4)

尝试此操作并确保com.tdk.web.exception.ResourceNotFoundException可以访问

Menu menu = menuService.findById(addMenuAmount.getMenuId())
                    .orElseThrow(() -> new com.tdk.web.exception.ResourceNotFoundException("menu "  + 
                            addMenuAmount.getMenuId() + " not found "));

注意lambda () ->,并用引号"menu "