Code in catch block not running despite an error occurred

#1

Hello,

I’ve a simple code in which I want to upload a file in in Amazon S3 bucket and then delete the file on my computer. The file is correctly uploaded to S3 but is not deleted after that. To discover why, I’ve put the code in a try/catch block to see what the error is.

try{
      val ListObjectsRequest = new ListObjectsRequest().withBucketName(BucketName).withPrefix("name_of_the_file")
      val credentials = new ProfileCredentialsProvider().getCredentials
      val S3 = AmazonS3ClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .withRegion("region_name")
        .build()
      val XMLFiles = S3.listObjects(ListObjectsRequest)
      XMLFiles.getObjectSummaries.forEach {
        XMLFile =>
          val KeyName = XMLFile.getKey
          UploadToBucket(S3, BucketName, KeyName, CsvSchema, getAMSSubscriberLogAttributes(getAMSSubscriberLogNodes(getXml(S3, BucketName, KeyName))))
          //KeyName = KeyName.split("/").last
          val FileToDelete = new File(KeyName)
          FileToDelete.delete()
    }

    }catch {
      case ioe: IOException =>
        System.err.println(ioe.getMessage)
        System.exit(1)
      case ase: AmazonServiceException =>
        System.err.println(ase.getErrorMessage)
        System.err.println(ase.getStatusCode)
        System.err.println(ase.getErrorCode)
        System.err.println(ase.getErrorType)
        System.err.println(ase.getRequestId)
        System.exit(1)
      case fnfe: FileNotFoundException =>
        println(fnfe.getMessage)
        System.exit(1)
    }

Unfortunately, no error message was displayed. Then, I decided to run the program in debug mode with a breakpoint on the delete file function. To test the catch block, I’ve deliberately entered a wrong file name. Then, I can noticed the debbuger is going to the “FileNotFoundException” block.

That’s where my problem appears : whatever the code I wrote in this block, nothing happened and the program ends normally without any error message and exit code 0 (which means that everything was ok)

I’ve tried a lot of things in the catch block but none of them worked. Can you help me ?

Thank you

#2

Have you looked at the javadoc for java.io.File#delete?

Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

The delete method you are calling—I think, I don’t know your imports—does not actually throw an Exception when a file cannot be deleted. It just returns false.

#3

OMG @Jasper-M thank you, I was stuck on that for 2 days. I had noticed that the return was false but never thought about the fact there was no error thrown.

Thank you so much and sorry for that question that seems so dumb now :blush:

#4

That’s ok. You can blame it on Java :smile: