Using exceptions
Exceptions are one of the mechanisms that we can use in Scala to handle error scenarios. It consists of two statements:
- The
throw exceptionObject
statement stops the current function and passes the exception up to the caller. - The
try { myFunc() } catch { case pattern1 => recoverExpr1 }
statement catches any exception thrown bymyFunc()
if the exception matches one of the patterns inside thecatch
block: - If an exception is thrown by
myFunc
, but no pattern matches the exception, the function stops, and the exception is passed up to the caller again. If there is notry...catch
block in the call chain that can catch the exception, the whole program stops. - If an exception is thrown by
myFunc
, and thepattern1
pattern matches the exception, thetry...catch
block will return therecoverExpr1
expression at the right of the arrow. - If no exception is thrown, the
try...catch
block returns the result returned bymyFunc()
.
This mechanism comes from Java, and since the Scala SDK sits on...