通用异常 e catch 覆盖特定异常 Java

Generic Exception e catch overwrites specific exception Java

throw new ResponseError(new DefaultResponse) 中产生错误时我抛出异常,当我输出消息时它看起来很好,但随后它被 catch(Exception e) 块覆盖。如果上面生成错误,我该怎么办忽略通用 catch

这是我的网络服务

@DELETE
@SecureIt
@Consumes(value = { MediaType.APPLICATION_JSON })
@Produces(value = { MediaType.APPLICATION_JSON })
@Path("/training-courses/{emptcId}")
@ApiOperation(value = "Delete training course",
              response = DefaultResponse.class,
                authorizations = {
                    @Authorization(
                        value="Bearer" 
                    )
                })
public Response deleteTrainingCourse(@ApiParam(value = "Employee Training Course Id", required = true) @PathParam("emptcId") Integer emptcId,
                                     @Context ContainerRequestContext crc)
throws ResponseError {
    ClsConnectionData connection = null;

    try 
    {
        String mToken = crc.getProperty("token").toString();
        connection = new ClsConnectionData(mToken);

        StatementWrapper sw = new StatementWrapper(connection)
            .createCall(" {CALL j2_employee.delete_training_course(?,?)} ")
            .bind(1,emptcId)
            .registerOutParameter(2, OracleTypes.CURSOR)
            .invoke();

        VoidResult voidResult = (VoidResult)sw.getSingleResultClass(2,VoidResult.class);

        if(voidResult.errorGenerated()) {
            throw new ResponseError(new DefaultResponse(ErrorCodes.DRIVEERROR.code(),
                                                        ResponseType.ERROR.getType(),
                                                        voidResult.getMessage(),
                                                        null));
        //At this point we are throwing the exception
        }
    }
    catch(Exception e)
    {
        //At the end this error is thrown
        System.out.println("Exception e = " + e);
        throw new ResponseError(e,true);
    }
    finally{
      connection.disconnect();
    }

    DefaultResponse dt = new DefaultResponse("0",
                                            ResponseType.SUCCESS.getType(),
                                            "",
                                            null); 
    return Response.ok(dt).build();
}

如果您想对一般异常进行特殊处理以区别于自定义异常,...

..then you have to catch ... (the custom) exceptions first! ...and then catch the more generalized... ones.

喜欢:

// ...
catch (ResponseError respErr) {
    System.out.println("ResponseError e = " + respErr);
    // re-throw! - no "new"!
    throw respErr;
}
catch (Exception e) {
    // but as @mndeveci mentioned: no good style!
    System.out.println("Exception e = " + e);
    throw new ResponseError(e, true);
}
// ...

catch(Exception e) 捕获在 try 块中抛出的 Exception.class 类型的任何异常或异常的子类。因此,您也将自己抛入 try-block 的异常。如果 ResponseError 是 Exception 的子类,那么它也会被捕获。

您可以在 try 之外抛出 ResponseError。如果您在 try 之前定义 voidResult 并检查 errorGenerated 之后,您将不再遇到该问题。你得到这样的东西:

VoidResult voidResult = null;
try {
    // some code getting to a voidResult
} catch (Exception e) { 
    // some code dealing with this eception
}
if (voidResult != null && voidResult.errorGenerated()) {
    // throw ResponseError
}

或者您应该确保 catch(Exception e) 不会捕获所有异常,而只会捕获更具体的异常。如果这是一个选项,它取决于实现代码。假设您的实现代码仅抛出 ConnectionExceptions(举个例子),您可以捕获 (ConnectionException) 而不是 Exception。如果 ResponseError 是 Exception 的子类,但不是 ConnectionException 的子类,它将不再被捕获。

您也可以这样做:

DefaultResponse errorResponse = null
try {
    // some code
    if (voidResult.errorGenerated()) {
        errorResponse = new DefaultResponse();
    }
} catch (Exception e) { 
    // deal with error
}
if (errorResponse != null) {
    throw new ResponseError////

最后你可以尝试看看你捕获的异常是否是你自己的异常并重新抛出它。

catch (Exception e) {
    if (e instanceof ResponseError && ((ResponseError) e).getCode.equals(myCode)) {
    throw e;
    else { // etc.