0

I have the following code:

var tempLastFileCreated: File = try { files(0) } catch { case e: ArrayIndexOutOfBoundsException => ??? } 

where files is val files: Array[File] = dir.listFiles()

Now whatever I give in case e I get the message Expression of type Unit doesn't conform to expected type File

I understand that the right hand part of the => has to be something which is of type File.

Can anyone tell me what to put there?

1 Answer 1

3

You are promising that tempLastFileCreated is a File, therefore it cannot also be a Unit or a String, etc. You have a couple options. You could use a Option[File] instead:

val tempLastFileCreated: Option[File] = try { Some(files(0)) } catch { case e: ArrayIndexOutOfBoundsException => None } 

Or if you wanted to store an error message, for example, another option is to use Either:

val tempLastFileCreated: Either[String, File] = try { Right(files(0)) } catch { case e: ArrayIndexOutOfBoundsException => Left("index out of bounds!") } 

Whatever bests suits your needs. You might want to take a look at Scala's scala.util.Try data type, which is safer. For example,

val tempLastFileCreated: Option[File] = Try(files(0)) match { case Success(file) => Some(file) case Failure(throwable) => None //or whatever } 
Sign up to request clarification or add additional context in comments.

7 Comments

How about .toEither and .toOption on a Try?
This does solve the problem but in a later part I used tempLastFileCreated.lastModified() which gives rise to problems no matter what I use whether it's Option[File] or Either[String, File]
@rbh-93 The problem is that you not longer have a File but an Option[File] or a Either[String, File] it is like trying to sum a String - it is a different data type, it has different methods... The idea behind abstractions like Try, Option and Either is to force the caller of the method to deal with errors, there are a couple of ways to do so, like: using any kind of getOrElse to retrieve the value given a default if the value is missing, using pattern matching to perform different actions for values and errors, or using higher order functions like map on them.
@LuisMiguelMejíaSuárez I understand the error now. Sorry if my questions sound quite stupid but I am very new to Scala. Is it possible to retain the lastModified() functionality while at the same time implementing exception handling of ArrayIndexOutOfBoundsException?
@rbh-93 No problem is okey, we all are learning something (Sorry if I sounded harsh, it was not my intention - English is not my native language, and I always had the impression I sound aggressive in it). Regarding your question, it depends in what you mean with "Error handling", more specifically who should deal with the error? Maybe tempLastFileCreated should always be a file, thus you may need to handle the error there using try / catch or Try, to provide a default value if something went wrong.
|