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

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.

主站蜘蛛池模板: 凌源市| 高碑店市| 东阳市| 灯塔市| 泗阳县| 长岭县| 萨嘎县| 大悟县| 泰和县| 山西省| 卓尼县| 正安县| 忻州市| 石台县| 深圳市| 宝应县| 怀仁县| 通城县| 陕西省| 大化| 淳安县| 舞钢市| 榕江县| 简阳市| 临夏县| 武山县| 伊金霍洛旗| 会理县| 双牌县| 正安县| 崇左市| 东兰县| 濮阳市| 乳山市| 灵宝市| 筠连县| 苍山县| 高阳县| 车致| 安西县| 米泉市|