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

The try... catch block

The Kotlin try... catch block is the equivalent of the Java try... catch block. Let's look at a quick example:

    fun sendFormData(user: User?, data: Data?) { // 1 
        user ?: throw NullPointerException("User cannot be null") 
// 2 data ?: throw NullPointerException("Data cannot be null") //do something } fun onSendDataClicked() { try { // 3 sendFormData(user, data) } catch (e: AssertionError) { // 4 // handle error } finally { // 5 // optional finally block } }
  1. Exceptions are not specified on function signature like in Java.
  2. We check the validity of the data and throw NullPointerException (notice that no new keyword is required when creating an object instance).
  3. The try... catch block is similar construct to Java.
  4. Handle only this specific exception (the AssertionError exception).
  5. The finally block is always executed.

There may be zero or more catch blocks and the finally block may be omitted. However, at least one catch or finally block should be present.

In Kotlin exception handling, try is an expression, so it can return a value and we can assign its value to a variable. The actual assigned value is the last expression of the executed block. Let's check if a particular Android application is installed on the device:

val result = try { // 1 
    context.packageManager.getPackageInfo("com.text.app", 0)  //2 
    true 
} catch (ex: PackageManager.NameNotFoundException) { // 3 
    false 
} 
  1. The try... catch block is returning value that was returned by a single expression function.
  2. If an application is installed, the getPackageInfo method will return a value (this value is ignored) and the next line containing the true expression will be executed. This is the last operation performed by a try block, so its value will be assigned to a variable (true).

If an app is not installed, getPackageInfo will throw PackageManager.NameNotFoundException and the catch block will be executed. The last line of the catch block contains a false expression, so its value will be assigned to a variable.

主站蜘蛛池模板: 定兴县| 阿拉尔市| 武山县| 邵武市| 房产| 电白县| 楚雄市| 泽州县| 政和县| 邵阳市| 耿马| 东光县| 建宁县| 罗山县| 平江县| 铅山县| 蓝山县| 莱芜市| 周宁县| 六安市| 连城县| 余干县| 涿鹿县| 托克逊县| 江川县| 惠州市| 嘉定区| 呼伦贝尔市| 呈贡县| 宜城市| 离岛区| 罗定市| 广丰县| 乃东县| 仪征市| 丁青县| 东阳市| 宁强县| 景德镇市| 岑溪市| 大足县|