aspire丶la aspire丶la - 4 months ago 13
Java Question

Return error code, msg or throw exception

I have a DBUtil class for jdbc, some method like query, insert and update, when some errors occur, we throw a RuntimeException now, but I have some questions.
When error occor, if I don't use try catch block to handle exception, I can't define whether it was succeed or not in code, so I can't do other things using the result, and controller will have no response rather than 500 error.

1:

try{

} catch(Exception e){
throw new RuntimeException("...")
}


2:

try{

} catch(Exception e){
log.error("..")
return someresult;// -1, empty list or others
}


so, which is better in code?
Thanks!

Answer

In any system not handling exceptions is not a good idea.

If you want centralized exception handling then you can throw exceptions from multiple parts of application and handle in centralized class/controller in such cases you can use

try{
} catch(Exception e){
    throw new RuntimeException("...")
}

in catch you can have custom exception classes with proper message and all

If you want handle exceptions right away then you can try

    try{

} catch(Exception e){
    log.error("..")
    return someresult;// -1, empty list or others
}

for e.g. if exception comes in try block you will be returning false otherwise true. Or null or blank message depends on implementation.

when you are re-throwing exception you can use finally to close resultsets/ open stream etc which is good practise

Comments