Let's write some code so that we can talk about exception handling. Take a look at the following:
def toInt(str: String): Int = str.toInt
In the preceding code, the toInt
is a function that takes a String
value, which supposedly can be converted to a corresponding Int
value. The definition looks okay, but as functional programmers, we are so used to trying out the function to see whether it does what it says (in the definition). Let's try out some calls to this function:
println(toInt("121")) println(toInt("-199"))
The preceding code gives the following result:
121 -199
Things worked fine for us. We passed a number in a string format and got the corresponding integer values. But what if you try something like the following:
println(toInt("+ -199"))
Say that we get something unexpected, some exception saying this:
Exception in thread "main" java.lang.NumberFormatException: For input string: "+ -199" at java.lang.NumberFormatException.forInputString(NumberFormatException...