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

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.

主站蜘蛛池模板: 屏东县| 夏河县| 瓦房店市| 翁牛特旗| 应用必备| 富顺县| 封丘县| 天峨县| 黄浦区| 合肥市| 黎川县| 肇庆市| 东安县| 泸定县| 苏尼特左旗| 井陉县| 肇源县| 博客| 乡宁县| 章丘市| 长春市| 方山县| 济阳县| 武威市| 金秀| 宁国市| 雅安市| 鹿邑县| 孟州市| 昭通市| 宁国市| 铅山县| 镇雄县| 红安县| 鸡泽县| 郧西县| 锦州市| 峨山| 观塘区| 贡觉县| 板桥市|