简体   繁体   中英

try and catch blocks in return methods

I'm fairly new to using try and catch statements and I'm having a bit of trouble with return statements. Upon compiling my code I got an unreported IOException in:
fileFtp = client.listNames(); So I tried wrapping this statement in a try and then wrote a catch for the exception but then the fileName array was no longer visible, so I wrapped the entire method in a try{} and used a catch at the end and put the return statement which returned the fileName after the end of the catch{} , but this didn't work either since fileName was no longer visible as it was in the try{} So how can I meet the exception report requirements while still having fileName and fileFtp arrays initialized?

 private String[] checkDirectories(){

    String[] fileFtp;
    String[] fileName;

    try{        
        fileFtp = client.listNames();
    }
    catch(IOException ex){
        System.out.println("IOException in checkDirectories()");
        ex.printStackTrace();     
    }

    fileName = new String[fileFtp.length];
        for (int i=0; i<fileFtp.length; i++){
            fileName[i] =   fileFtp[i];
        }            
        return fileName;
 }

You shouldn't be catching the exception here, when you do that you don't give the calling code any indication that the operation failed. Let the exception be thrown so that the caller can realize that something went wrong and deal with it:

private String[] checkDirectories() throws IOException {

    String[] fileFtp = client.listNames();
    String[] fileName = new String[fileFtp.length];
    for (int i=0; i<fileFtp.length; i++) {
        fileName[i] =   fileFtp[i];
    }
    return fileName;
}

Throwing an exception lets the code get out of its current path of execution so that it's not operating on invalid data, and it signals to calling code that something went wrong. If you catch the exception and return null here than calling code has to check for null and decide whether or not to proceed.

I am not sure what you asked but you should probably try this:

private String[] checkDirectories()
{

    String[] fileFtp = null;
    String[] fileName = null;
    try
    {
    fileFtp = client.listNames();
     fileName = new String[fileFtp.length];
        for (int i=0; i<fileFtp.length; i++)
        {
            fileName[i] =   fileFtp[i];
        }
    }
        catch(IOException ex)
{
    System.out.println("IOException in checkDirectories()");
    ex.printStackTrace();

}



        return fileName;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM