Is it a good idea to contain everything in a test

advertisements

I am using java, and all exceptions in my codes are derived from java.lang.exception. Is it a good idea to contain everything in one try-catch? Is it a good idea to add try-catch for every difficult function?

Because I want to let my codes run better in a lazy way, which means no exceptions will cause my program crash, e.g., catch IndexOutOfBoundsException, ArrayIndexOutOfBoundsException,SQLGrammarException ......

following are my codes:

public MyResult function1(){
    MyResult myResult = new MyResult();
    try{
        //all codes here
    }catch(Exception e){
        LOGGER.error(e);
        myResult.setException(e);
    }finally{
        return myResult;
    }
}

//more same functions using same try-catch here

public MyResult functionN(){
    MyResult myResult = new MyResult();
    try{
        //all codes here
    }catch(Exception e){
        LOGGER.error(e);
        myResult.setException(e);
    }finally{
        return myResult;
    }
}


all exceptions in my codes are derived from java.lang.Exception

This may not be a good idea, because there is a class of exceptions that needs to be defined from java.lang.RuntimeException - namely, exceptions that indicate programming errors, i.e. situations that require changing the program in order to be fixed.

Is it a good idea to contain everything in one try-catch?

No, it is not. You should add try/catch as needed, placing them around the blocks of code that may throw them, and only in situations where your code is prepared to handle the exception in some meaningful way.

Is it a good idea to add try-catch for every difficult function?

You should not place try/catch inside methods that do not know how to handle the exception. A better approach is to let the exception go up the invocation chain until it hits the method that is prepared to handle the exception.

There are situations when such method would be at the very top of the invocation chain, in which case the method often logs and exits or returns an error status.