Tag: try catch

为什么Kotlin收到这样的UndeclaredThrowableException而不是ParseException?

我有一个extension方法,将字符串转换为Kotlin中的日期。 fun String.convertToDate() : Date { var pattern: String = "dd-mm-yyyy" val dateFormatter = SimpleDateFormat(pattern) return dateFormatter.parse(this) // parse method throw ParseException } 这是我试图捕捉可能的异常的代码。 try { "22—2017".convertToDate() } catch (ex: ParseException) { // ParseException supposed to be caught in this block logger.error("Parse exception occur") } catch (ex: Exception) { // ParseException caught in this block […]

Kotlin检查了例外情况

由于Kotlin不支持检查异常,所以如何让程序员意识到一个方法可能会抛出异常 简单的例子: class Calculator (value: Int = 0) { fun divide (dividend: BigDecimal, divider: BigDecimal) : BigDecimal { return dividend / divider } } 显然,除法方法可能会抛出java.lang.ArithmeticException: Division by zero异常,并且库的创建者需要警告类的用户将调用置于try-catch子句中 Kotlin的这种意识的机制是什么?