zoukankan      html  css  js  c++  java
  • [Kotlin] Try catch & Throw

    In java, it requires you to handle the exception when you declaring and using the code:

    public class BoringJavaCode {
        public static Double divide(int a, int b) throws InterruptedException {
            Thread.sleep(1000);
            return (double)a / b;
        }
    
        public static void main(String args[]) {
            try {
                System.out.println(divide(6,3));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    but in kotlin, it is not requried. Kotlin has @Throws(), but it is only for Java developer to know that they need to handle that exception.

    // for java to check the code
    @Throws(InterruptedException::class)
    fun main(args: Array<String>) {
        var result = try {
            // but kotlin doesn't require you mention throw
            divide(5, 23)
        } catch(e: Exception) {
            println(e)
            0 // return value
        }
    
        println(result)
    }

    fun divide (a: Int, b: Int): Double {
    Thread.sleep(1000)
    return (a.toDouble()) / b
    }
     
  • 相关阅读:
    生成器
    迭代器
    装饰器
    闭包函数
    函数对象
    函数
    文件
    字符编码
    基本的数据类型和内置方法02
    基本的数据类型和内置方法01
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13900100.html
Copyright © 2011-2022 走看看