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

Exception handling

Handling of exceptions is almost identical to the way Java handles exceptions with one key difference-in Kotlin all exceptions are unchecked.

As a reminder, checked exceptions are those that must be declared as part of the method signature or handled inside the method. A typical example would be IOException, which is thrown by many File functions, and so ends up being declared in many places throughout the IO libraries.

Unchecked exceptions are those that do not need to be added to method signatures. A common example would be the all too familiar NullPointerException, which can be thrown anywhere. If this was a checked exception, literally every function would need to declare it!

In Kotlin, since all exceptions are unchecked, they never form part of function signatures.

The handling of an exception is identical to Java, with the use of try, catch, and finally blocks. Code that you wish to handle safely can be wrapped in a try block. Zero or more catch blocks can be added to handle different exceptions, and a finally block is always executed regardless of whether an exception was generated or not. The finally block is optional, but at least one catch or finally block must be present.

In this example, the read() function can throw an IOException exception, and so we may wish to handle this potential exception in our code. In this case, we assume the input stream must always be closed, regardless of whether the reading is successful or not, and so we wrap the close() function in a finally block:

    fun readFile(path: Path): Unit { 
      val input = Files.newInputStream(path) 
      try { 
        var byte = input.read() 
        while (byte != -1) { 
          println(byte) 
          byte = input.read() 
        } 
      } catch (e: IOException) { 
        println("Error reading from file. Error was ${e.message}") 
      } finally { 
        input.close() 
      } 
    } 
主站蜘蛛池模板: 镇雄县| 达拉特旗| 长宁区| 仁化县| 泸定县| 万盛区| 淮滨县| 项城市| 乌拉特后旗| 油尖旺区| 高雄市| 莱芜市| 湾仔区| 永康市| 安宁市| 隆昌县| 融水| 扶风县| 明光市| 晋州市| 衡南县| 司法| 武宣县| 溧水县| 老河口市| 唐河县| 荔波县| 五寨县| 乐陵市| 利辛县| 永康市| 宿迁市| 上高县| 登封市| 京山县| 乐平市| 浦江县| 徐水县| 新源县| 钦州市| 鹿泉市|