CodeGym /Kurslar /Kotlin SELF /Oz istisnalarin ve esas sebeb

Oz istisnalarin ve esas sebeb

Kotlin SELF
Səviyyə, Dərs
Mövcuddur

1. Niye “texniki istisna” cox vaxt faydasiz olur

Eger siz yeni baslayirsinizsa, istisnalar cox vaxt “yasamaga mane olan qirmizi herfler” kimi gorunur. Amma problem istisnanin bas vermesinde deyil, problem ondadir ki, istisna mesaji cox vaxt sizin vezifeniz haqqinda hec ne demir. Komputer duzunu deyir: “men setri edede cevire bilmedim”, siz ise oturub fikirlashirsiniz: “yaxsi... amma harada, niye mehz orada ve istifadeci ne daxil edib?”.

Tesevvur edin ki, sizde konsol tetbiqi var ve istifadeci komandalar daxil edir, meselen:

add coffee 120

Eger istifadeci bele daxil etse:

add coffee twelve

onda tipik asagi-seviyye “partlayis” NumberFormatException olacaq. Problem ondadir ki, bu mesaj “eded deyil” — dogrudur, amma cox umumi. Sizin tetbiqinizde ise daha vacib olan budur: “xerc meblegi eded olmalidir”, ve mumkunse hansi deyerin geldiyini de gostermek yaxsidir.

Yeni biz isteyirik ki, sehv muellimin (xeyirxah) dediyi cumeleye oxsasin: “Xercin meblegi tam eded olmalidir, amma siz twelve daxil etdiniz”. Kompilyatorun cümlesine yox (o da xeyirxahdir, sadəcə xasiyyeti var): “NumberFormatException”.

2. cause ve sebebler zenciri

Siz istisnani tutub baska — daha anlasilan — istisna atmaq qerarina gelende, klassik sehv etmeyiniz mumkundur: esas sebebi itirmek. Esas sebeb (JVM-de ona adeten cause deyirler) — her seyin baslamasina sebeb olan “orijinal qezadir”.

Kotlin/Java-da istisna — basqa bir istisnaya istinad saxlayan obyektdir: “men yixildim, cunki bu yixildi”. Kotlin senedlesdirilmesi vurgulayir ki, oz mesajlarinizi yaza bilersiniz ve eyni zamanda orijinal cause-u saxlayib onun stack trace-e dusmesine nail ola bilersiniz.

Vizual olaraq bu, zencire benzer:

CommandParseException("Amount must be a number, got 'twelve'")
    caused by NumberFormatException("For input string: \"twelve\"")

Ve bu zencir debug ucun qizildir. Istifadeciye yalniz yuxari seviyye (“mebleg eded olmalidir”) gosterirsinizse bele, proqramciya (yeni gecenin saat 2-sinde bug duzelden gelecek size) esas sebebi bilmek cox faydalidir.

Kicik axin sxemi (beli, bu ele o andir ki, blok-sxem dogrudan da komek edir):

flowchart TD
    A["Asagi-seviyye kod: toInt()"] -->|atir| B["NumberFormatException"]
    B --> C["catch(e)"]
    C --> D["throw CommandParseException(..., cause=e)"]
    D --> E["yuxari seviyye CommandParseException-i tutur"]
    E --> F["istifadeci aydin mesaji gorur"]
    E --> G["proqramci istese cause zencirini gorur"]

3. Oz istisnalarinizi nece elan etmek olar

Biz “oz istisna” deyende, bu “tecili 48 siniflik iyerarxiya qurmaq” demek deyil. Adeten tetbiqin her seviyyasi ucun 1–2 sinif kifayet edir.

Kotlin-de oz istisnaniz — Exception (ve ya basqa istisna) sinifinden irs alan adi sinifdir. Kotlin senedlesdirilmesi custom exceptions yaratmani mehz bele tesvir edir.

Bizim meqsedlerimiz ucun en praktik shablon — message ve opsional cause qebul etmekdir:


class CommandParseException(
    message: String,
    cause: Throwable? = null
) : Exception(message, cause)

Iki meqama diqqet edin.

Birinci: biz Throwable? isledirik, Exception? yox. Bu JVM-dunyasi ucun daha adidir: cause her hansi “atilabilen” obyekt ola biler.

Ikinci: defolt null o demekdir ki, istisnani esas sebebsiz de ata bilirik — eger onu ozumuz “sifirdan” formalaşdırmisiqsa.

Niye object MyException : Exception(...)

Bazen yeni baslayan biri Kotlin-in object bacardigini gorub bele dusunur: “O! Hamisi ucun bir istisna edim ki, obyekt coxalmansin”. Bu, pis fikirdir. Istisnalar — vəziyyet + stack trace-dir, ve Kotlin senedlesdirilmesi aciq sekilde meslehet gorur ki, istisnalari object ile deyil, her defe yeni nüsxe kimi yaradın ki, vəziyyet real konteksti eks etdirsin.

4. Wrapping: tutdu, kontekst elave etdi, yeniden yuxariya atdi

Gelin bu seviyyenin esas usulunu berkitdək: biz asagi-seviyye sehvini tuturuq ve yeni, amma artıq “tetbiqimizin dilinde” olan istisna atiriq. Bu zaman mutleq cause-u otururuk.

Numune: xerc meblegini pars edirik ve mena elave edirik

fun parseAmount(text: String): Int {
    val prepared = text.trim()

    try {
        return prepared.toInt()
    } catch (e: NumberFormatException) {
        throw CommandParseException("Amount must be an integer, got '$text'", e)
    }
}

Burada vacib olan budur ki, biz esas sebebi gizletmirik. Aydin mesaj elave etdik, amma e-ni cause kimi saxladıq.

Numune: “sebebsiz ortuk” — izleri nece itirmek olar

Bezen bele yazirlar:

fun parseAmountBad(text: String): Int {
    return try {
        text.trim().toInt()
    } catch (e: NumberFormatException) {
        throw CommandParseException("Bad amount") // cause itirildi
    }
}

Bu variantin menfi terefi ondadir ki, yuxarida haradasa siz neyin geldiyini ve niye toInt()-in yixildigini anlamaq isteseniz, artıq ilkin istisna ve onun detallari yoxdur.

Numune: ne vaxt kontekst “tip”den daha vacibdir

Texniki olaraq NumberFormatException onsuz da “eded” haqqindadir. Amma sizin tetbiqinizde bir nece eded ola biler: mebleg, limit, say, ay nomresi, istifadeci ID-si. Bu halda “eded deyil” — faydasizdir. Ona gore de biz CommandParseException edirik ki, menani ayiraq: “komanda pars xetasi”.

5. Mini-tetbiq: xercler trekkeri ve aydin sehvler

Indi biz tedris tetbiqimizin kicik, amma bütöv bir hissesini yigacagıq. Qoy bu, en sade xerc trekkeri olsun: xerclerin siyahisini yaddasda saxlayir ve komandalar qebul edir:

add <title> <amount>
list
exit

Biz memariligi tavanadek qatlara bolmeyeceyik — bugunku meqsedimiz “ideal sistem” deyil, praktika: sehv harada ortulmelidir ve cause nece itirilmeyib saxlanilmalidir.

Melumat modeli ve yaddasda saxlanan anbar

Evvelki gunlerde bizde artıq sinifler ve obyekt kolleksiyalari var idi, ona gore sade model qururuq:

data class Expense(
    val title: String,
    val amount: Int
)

Ve anbar kimi siyahi:

val expenses = mutableListOf<Expense>()

Tetbiq seviyyeli oz istisnalar

Biz iki nov istisna yaradaq: biri komanda daxil etmə xetalarina gore, digeri isə məntiqi olaraq mumkun olmayan veziyyetlere gore (bu gun ikincisi demek olar ki, lazim olmayacaq, amma ferqi gormek faydalidir).

class CommandParseException(message: String, cause: Throwable? = null) : Exception(message, cause)

class AppStateException(message: String, cause: Throwable? = null) : Exception(message, cause)

Komanda parseri: struktur qaytaririq ve ya istisna atiriq

Kod oxunaqli olsun deye, pars olunmus komandani tip kimi tesevvur etmek rahatdir. Biz artıq sealed class bilirik, ona gore bele edek:

sealed class Command {
    data class Add(val title: String, val amount: Int) : Command()
    data object ListAll : Command()
    data object Exit : Command()
}

Indi pars funksiyasi:

fun parseCommand(line: String): Command {
    val parts = line.trim().split(" ").filter { it.isNotBlank() }

    if (parts.isEmpty()) throw CommandParseException("Empty command")

    return when (parts[0].lowercase()) {
        "add" -> parseAdd(parts)
        "list" -> Command.ListAll
        "exit" -> Command.Exit
        else -> throw CommandParseException("Unknown command: '${parts[0]}'")
    }
}

Burada biz CommandParseException-i “birbasa” atiriq — asagi-seviyye esas sebeb yoxdursa: problemi ozumuz askar etdik.

Indi ise en maraqlisi — parseAdd.

parseAdd: NumberFormatException-i aydin xetaya orturuk

fun parseAdd(parts: List<String>): Command.Add {
    if (parts.size < 3) {
        throw CommandParseException("Usage: add <title> <amount>")
    }

    val title = parts[1]
    val amountText = parts[2]

    val amount = try {
        amountText.toInt()
    } catch (e: NumberFormatException) {
        throw CommandParseException("Amount must be a number, got '$amountText'", e)
    }

    return Command.Add(title = title, amount = amount)
}

Diqqet edin: biz parseAmount(...)-i cagira bilerdik, amma indi texnikani mehz istifade yerinde gosteririk ki, “tutdu → cause ile atdi” aydin gorunsun.

Esas dovr: yalniz gozlənilənleri tuturuq

Indi main. Evvel müzakire etdiyimiz stile gore, biz “her seyi” tutmaq istəmirik. Yalniz gozlənilən pars xetalarini tuturuq.

fun main() {
    val expenses = mutableListOf<Expense>()

    while (true) {
        print("> ")
        val line = readln()

        try {
            when (val cmd = parseCommand(line)) {
                is Command.Add -> {
                    expenses.add(Expense(cmd.title, cmd.amount))
                    println("Added: ${cmd.title} (${cmd.amount})") // Added: coffee (120)
                }
                Command.ListAll -> {
                    printExpenses(expenses)
                }
                Command.Exit -> return
            }
        } catch (e: CommandParseException) {
            println("Input error: ${e.message}") // meselen: Input error: Amount must be a number, got 'twelve'
            // Tedris meqsedleri ucun muveqqeti olaraq esas sebebi cap etmek olar:
            // println("Cause: ${e.cause?.javaClass?.simpleName}") // Cause: NumberFormatException
        }
    }
}

printExpenses-i qisa ve tehlukesiz edek:

fun printExpenses(expenses: List<Expense>) {
    if (expenses.isEmpty()) {
        println("(empty)") // (empty)
        return
    }

    for (e in expenses) {
        println("- ${e.title}: ${e.amount}") // - coffee: 120
    }
}

6. require/check vs oz istisnalar

Bir muddet sonra sizde bele bir hiss yaranacaq: “Eger require() var, niye mene oz istisnalar lazimdir?”. Bu ela sualdir, cunki mehz burada “validasiya” ile “kontekst” arasindaki yetkin serhed gorunur.

require(...) ve check(...) — standart istisnalar atan predikatlardir: IllegalArgumentException ve IllegalStateException. Kotlin senedlesdirilmesi onlarin təyinatini ve hansi istisnalari atdigini yaxsi izah edir.

Insan dili ile desek, require — “sen mene pis giris vermisen, men islemeye borclu deyiləm”, check ise — “mende daxilde pis veziyyet var, bu kodda mentiqi sehvdir”.

Oz istisnalar ise cox vaxt bashqa noqtede lazim olur: siz predmet sahenizin menali sehvini ayirmaq isteyirsiniz. Meselen, “komanda taninmadi”, “menfi meblegle xerc elave etmek olmaz”, “kateqoriya movcud deyil”. Bele hallarda oz istisna tipiniz komek edir:

  • birincisi, onu ayrica tutmaga (ve basqalari ile qarisdirmamaga),
  • ikincisi, mesajlar ucun vahid stil vermeye,
  • ucuncusu, sehv “asagidan” gelibse cause-u saxlamaga.

Meselen, menfi meblegleri qadağan etmek isteseniz, bunu bele de etmek olar:

fun validateAmount(amount: Int): Int {
    require(amount > 0) { "Amount must be > 0, got $amount" }
    return amount
}

Bu ela variantdir, cunki menfi mebleg — onsərtin (precondition) pozulmasidir.

Amma siz komanda pars edirsinizse ve “pars xetasi”ni diger problemlerden ayirmaq isteyirsinizse, CommandParseException daha yaxsi oxunur.

Mini-diaqnostika: sebebler zencirine nece baxmaq olar

Bezen siz istifadecige qisa mesaj gostermek isteyirsiniz, amma ozunuz ucun (ve ya tedris rejiminde muveqqeti diaqnostika ucun) cause zencirini cap etmek isteyirsiniz. Kotlin-de her Throwable-in cause-u var: Throwable?.

7–8 setirlik kicik funksiya yazaq ki, “sebebler pilləkəni”ni cap etsin. Fanatizm olmadan:

fun printCauseChain(e: Throwable) {
    var current: Throwable? = e
    while (current != null) {
        println("${current::class.simpleName}: ${current.message}")
        current = current.cause
    }
}

Eger bele cagirsaq:

try {
    parseCommand("add coffee twelve")
} catch (e: CommandParseException) {
    printCauseChain(e)
}

onda texminən bele bir sey goreceksiniz:

CommandParseException: Amount must be a number, got 'twelve'
NumberFormatException: For input string: "twelve"

Ve bu yaxsi kompromisdir: istifadeciye qorxunc detallari gostermirsiniz, amma inkisaf rejiminde tez bir zamanda ne bas verdiyini anlayirsiniz.

7. Tipik sehvler

Sehv № 1: istisnani ortub cause-u itirmek.
Siz NumberFormatException-i tutub oz istisnanizi cause-u oturmeden atanda, gozel mesaj qazanirsiniz, amma arasdirma imkanini itirirsiniz. Bir nece hefte sonra siz CommandParseException("Bad amount") goreceksiniz ve hiss edeceksiniz ki, bu sehv “men ne oldugunu bilmirəm, amma oldu” kimi yazilib. Esas sebebi ikinci arqument kimi oturun (Exception(message, cause)), Kotlin ve JVM bu elaqeni saxlaya bilir.

Sehv № 2: butun hallar ucun bir istisna yaratmaq.
Bezen bele bir cazibe yaranir: “AppException edim ve her defe onu atim”. Neticede istisna tipi nese ifade etmir, ve siz yenidən her seyi mesaj metnine gore ferqlendirmeli olursunuz. En azi bir menali tipiniz olsun, meselen daxil etmə/pars xetalari ucun CommandParseException, ve onu sabit sekilde istifade edin.

Sehv № 3: “alloc etməmək” ucun istisnalari object kimi yaratmaq.
Istisna stack trace ve yaranma kontekstini ozunde saxlayir. Eger siz singleton-istisna yaratsanız, o, proqramda heqiqeten bas vermis konteksti deyil, tamam baska konteksti saxlayacaq ve diaqnostika qeribe olacaq. Kotlin senedlesdirilmesi aciq sekilde xeberdar edir ki, istisnalar stateful-obyektlerdir ve onlar yeni nüsxe kimi yaradilmalidir.

Sehv № 4: cox genis tip tutub “dunyadaki her seyi duzeltmek”.
catch (e: Exception) ile main-in yarisini əhatə etmek “muhafize kupolu” kimi gorunur, amma praktikada “sehv supurgesi”ne cevrilir: siz tesadufen yixilmasi ve duzeltilmesi gereken bug-lari uda bilersiniz. Bugunku texnika mehz cause haqqindadir: yalniz gozlədiyiniz seyləri tutun (meselen, CommandParseException), qalanlari ise yixilsin — bu, proqramci ucun siqnaldir.

Sehv № 5: faktiki deyerler olmadan istisna mesaji.
"Bad amount" kimi mesaj “pis nese” kimi səslənir. "Amount must be a number, got 'twelve'" kimi mesaj ise nəyi duzeltmek lazim oldugunu deyir ve diaqnostika ucun melumat saxlayir. Mesajlari “ne gozleyirdik” + “ne aldiq” formulasina gore yazmaga calisin.

Sehv № 6: onsərtleri (preconditions) ve ssenari xetalarini bir-birine qarisdirmamaq.
Eger siz require-i her sey ucun isletseniz, tezlikle semantikanı itireceksiniz: harada istifadecinin daxil etmə xetasi var, harada mentiqi bug var, harada ssenari probleminiz var. Yaddan cixarmayin ki, require()/check() — giris ve vezziyyet haqqindadir (ve standart istisnalar atir). Oz istisnalar ise tetbiqin “dilinde” sehvleri ifade etmek istediyiniz yerde ve lazim olduqda esas sebebi saxlamaq ucun faydalidir.

1
Tapşırıq
Kotlin SELF, səviyyə, dərs
Bağlanıb
Forma xətası
Forma xətası
1
Tapşırıq
Kotlin SELF, səviyyə, dərs
Bağlanıb
Məhsulun miqdarı
Məhsulun miqdarı
1
Tapşırıq
Kotlin SELF, səviyyə, dərs
Bağlanıb
Konsol komandası
Konsol komandası
1
Tapşırıq
Kotlin SELF, səviyyə, dərs
Bağlanıb
Səbəblər zənciri
Səbəblər zənciri
Şərhlər
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION