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 by myFunc() if the exception matches one of the patterns inside the catch 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 no try...catch block in the call chain that can catch the exception, the whole program stops.
  • If an exception is thrown by myFunc, and the pattern1 pattern matches the exception, the try...catch block will return the recoverExpr1 expression at the right of the arrow.
  • If no exception is thrown, the try...catch block returns the result returned by myFunc().

This mechanism comes from Java, and since the Scala SDK sits on top of the Java SDK, many function calls to the SDK can throw exceptions. If you are familiar with Java, the Scala exception mechanism differs slightly. Exceptions in Scala are always unchecked, which means that the compiler will never force you to catch an exception or declare that a function can throw an exception.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset