[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
}
 
原文地址:https://www.cnblogs.com/Answer1215/p/13900100.html