简体   繁体   中英

Why does `scala.util.Try(date)` not return `Failure` when `date` is not defined?

Why does scala.util.Try(date) not return Failure as I would expect like how scala.util.Try(3/0) returns Failure(java.lang.ArithmeticException: / by zero) ?

This is what I'm seeing in my REPL

scala> scala.util.Try(3/0)
res5: scala.util.Try[Int] = Failure(java.lang.ArithmeticException: / by zero)

scala> scala.util.Try(date)
                      ^
       error: not found: value date

It's sort of difficult to tell the difference because runtime happens right after compile time in the REPL, but it's because missing value date is a compile time error, and a Failure represents a runtime error.

scala.util.Try(date)
not found: value date

is silly compiler error (you have not declared date varialble and you are using it) not Runtime Exception Where as

scala.util.Try(3/0) 

Failure(java.lang.ArithmeticException: / by zero): scala.util.Try[Int]

runtime exception

See another examples: Example 1:

val dateFmt1 = "yyyyy   xx"
scala.util.Try {  
    val date = new Date
    val sdf = new SimpleDateFormat(dateFmt1)
    sdf.format(date)
}

will throw RuntimeException like this

    Failure(java.lang.IllegalArgumentException: Illegal pattern character 'x'): scala.util.Try[String]

Example 2:

val dateFmt = "yyyy-MM-dd"
scala.util.Try {  
    val date = new Date
    val sdf = new SimpleDateFormat(dateFmt)
    sdf.format(date)
}

will result:

Success(2020-04-30): scala.util.Try[String]

See exception handing article here for better understanding

Consider the expression Try(x) where, in this case, x can be a variable to be evaluated, or a function to be invoked, or a block of code to be executed. This expression will return Failure if x (whatever it is) throws an exception.

Throwing an exception is a runtime event.

If, on the other hand, x is a reference to a variable or function that doesn't exist, or x as a block of code can't be compiled because it has a syntax error, then that's a compile-time error. In that case the Try() call is never even invoked because the compiler has nothing to pass as the specified argument.

The REPL (Read-Evaluate-Print-Loop) can obscure the difference between the two types of errors because the compile->run (evaluate->print) happens, one after the other, with each line of input.

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