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

  • Android Development with Kotlin
  • Marcin Moskala Igor Wojda
  • 428字
  • 2021-07-02 18:48:39

Exceptions

Most Java programming guidelines, including the book Effective Java, promote the concept of validity checks. This means that we should always verify arguments or the state of the object and throw an exception if a validity check fails. Java exception systems have two kinds of exceptions: checked exceptions and unchecked exceptions.

An unchecked exception means that the developer is not forced to catch exceptions by using a try... catch block. By default, exceptions go all the way up the call stack, so we make decisions where to catch them. If we forget to catch them, they will go all the way up the call stack and stop thread execution with a proper message (thus they remind us):

Java has a really strong exception system, which in many cases forces developers to explicitly mark each function that may throw an exception and explicitly catch each exception by surrounding them with try... catch blocks (checked exceptions). This works great for very small projects, but in real large-scale applications, this very often leads to the following verbose code:

    // Java 
    try { 
        doSomething() 
    } catch (IOException e) { 
        // Must be safe 
    } 

Instead of passing the exception up in the call stack, it is ignored by providing an empty catch block, so it won't be handled properly and it will vanish. This kind of code may mask critical exceptions, give a false sense of security, and lead to unexpected problems and difficult to find bugs.

Before we discuss how exception handling is done in Kotlin, let's compare both types of exception:

Code

Checked exceptions

Unchecked exceptions

Function declaration

We have to specify what exceptions can be thrown by functions.

The function declaration does not contain information about all thrown exceptions.

Exception handling

The function that throws an exception must to be surrounded by a try... catch block.

We can catch the exception and do something if we want, but we aren't forced to do this. The exception goes up in the call stack.

 

The biggest difference between the Kotlin and Java exception systems is that in Kotlin all exceptions are unchecked. This means we never have to surround a method with a try... catch block, even if this is a Java method that may throw a cached exception. We can still do it, but we are not forced to:

    fun foo() { 
        throw IOException() 
    } 
 
    fun bar() { 
        foo () //no need to surround method with try-catch block 
    } 

This approach removes code verbosity and improves safety because we don't need to introduce empty catch blocks.

主站蜘蛛池模板: 大连市| 青海省| 定远县| 乌审旗| 南开区| 苗栗县| 枣庄市| 合水县| 凌海市| 淳安县| 林州市| 太康县| 泗水县| 旌德县| 安塞县| 隆子县| 同江市| 蒲城县| 分宜县| 上虞市| 英吉沙县| 焉耆| 鹤壁市| 安平县| 黄梅县| 象州县| 来凤县| 咸丰县| 浦城县| 晋宁县| 尤溪县| 花莲县| 宁国市| 横峰县| 修武县| 呈贡县| 盘锦市| 曲靖市| 礼泉县| 汶川县| 望都县|