Why does getFile() in org.springframework.core.io.AbstractResource throw an exception?

65 Views Asked by At

First of all, please understand that sentences can be strange because I use a translator.

I tried to use the getFile() method of the resource object returned by getResource() in multipartFile while implementing the Image Upload feature, but it is configured to throw an exception. I wonder why it is like this.

I've read Java Doc, but I can't tell because it only says that I'm throwing an exception

2

There are 2 best solutions below

0
Mar-Z On BEST ANSWER

Let me try to understand your problem and help you.

The method getFile() is declared as "throws an exception". It doesn't mean it will throw an exception in any case. It just means that it CAN throw an exception under certain circumstances. This will force you as a programmer to implement some error handling logic. Usually in form of a try/catch block.

In this particular case the file should be "physically" accessed for reading. In a rare case it is not accessible or even doesn't exist anymore - you will get an exception and should handle it.

That's it all about. I hope it helps.

0
srivathsa On

The abstract class AbsractResource overrided the method getFile() which was inherited from the Interface Resource.

The reason why getFile() method of Interface Resource throws exceptions is,

  • If there is a failure in reading of the file or in case of general resolution/reading failures the method throws IOException.

The implementation class i.e AbsractResource also throws an exception

  • If the resource is not available in the file system the method throws FileNotFoundException by giving "description " and this message " cannot be resolved to absolute file path".

Note: While IOException is a part of the method signature whereas FileNotFoundException is thrown in the implementation of the method.

Hope this helps.