Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Ném Custom Exception trong Kotlin

Giới thiệu

Exception (ngoại lệ) là khía cạnh quan trọng ngăn chặn output sai tại runtime. Tất cả exception trong Kotlin đều kế thừa từ class Throwable. Kotlin cho phép tạo Custom Exception (ngoại lệ tùy chỉnh) thuộc nhóm unchecked exception (ném tại runtime).

Checked vs Unchecked Exception

Checked Exception (kiem tra compile-time)

Ví dụ: FileNotFoundException, IOException.

import java.io.File
import java.io.InputStream

fun main(args: Array<String>) {
    try {
        val inputStream: InputStream = File("Hello.txt").inputStream()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

Unchecked Exception (runtime)

Ví dụ: ArithmeticException, NumberFormatException.

fun main(args: Array<String>) {
    try {
        val myVar: Int = 12
        val v: String = "Tutorialspoint.com"
        v.toInt()
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        println("Exception Handling in Kotlin")
    }
}

Custom Exception trong Kotlin

Tạo class exception kế thừa Exception.

fun main(args: Array<String>) {
    val sampleNumber: Int = 100
    if (sampleNumber > 50) {
        throw myCustomException("Invalid Inputs - Please enter a correct number")
    } else {
        println("Welcome !! you have entered a correct value")
    }
}

// Khai báo custom exception
class myCustomException(message: String) : Exception(message)

Kết quả

Exception in thread "main" myCustomException: Invalid Inputs - Please enter a correct number
    at MainKt.main(main.kt:7)

Custom exception cho phép định nghĩa lỗi nghiệp vụ riêng, dễ dàng bắt và xử lý.