有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在使用转换器时无法从“convertToDatabaseColumn”引发异常

我正在为一个类制作一个转换器,其中包括解析JSON。如果json解析失败,我想抛出异常,但它只允许我尝试/捕获异常。我需要将异常抛出到上层,以便传播错误。我尝试在函数中添加抛出,但它说这是不允许的。有没有办法将异常传播到上层

    @Converter( autoApply = true)
    public static class classConverter implements AttributeConverter<Class, String> {
        
        @Override
        public String convertToDatabaseColumn(Class classobj) {
                        
            ObjectMapper object = new ObjectMapper();
            String json = new String();

                try {
                    json = object.writeValueAsString(classobj);
                } catch (JsonProcessingException e) {
                    // Gives error when i try to throw the error
                    throw e;

                }

            
            return json;
            
        }

共 (1) 个答案

  1. # 1 楼答案

    你可以把它包装成一个子类RuntimeExcpetion

    声明一个新的RuntimeException

    public class JsonProcessingRuntimeException extends RuntimeExcpetion{
    }
    

    把它扔到你的课堂上:

    } catch (JsonProcessingException e) {
        // Gives error when i try to throw the error
        throw new JsonProcessingRuntimeException (e);
    
    }
    

    在上层你可以捕捉到JsonProcessingRuntimeException