官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 拉萨市| 潼关县| 南靖县| 淳安县| 凤凰县| 离岛区| 和静县| 晋宁县| 屯门区| 江口县| 淳安县| 阿克陶县| 砀山县| 荥经县| 鄂伦春自治旗| 克东县| 顺平县| 修水县| 辽源市| 寿光市| 始兴县| 革吉县| 武威市| 斗六市| 锡林浩特市| 中西区| 衡阳市| 大足县| 永胜县| 虞城县| 万安县| 敦煌市| 彭山县| 汨罗市| 仁寿县| 蒙山县| 额济纳旗| 桂林市| 铁岭县| 台前县| 南漳县|