OCA Java imtahan mövzuları

Calling Methods That Throw Exceptions

Əgər metod exception fırladırsa, həmin metodu çağıran zaman bəzi qaydalara riayət edilməlidir.

class NoCarrotException extends Exception {}

public class Bunny {

    public static void main(String[] args) {
        eatCarrot();  // DOES NOT COMPILE
    }

    private static void eatCarrot() throws NoCarrotException {
    }
}

Bu kod ona görə compile xətası verir ki,  NoCarrotException checked exceptiondur. Checked exceptionlar mütləq handle və ya declare olunmalıdır. Əgər main metodu aşağıdakı formalarda dəyişsək, kod compile olunacaqdır:

public static void main(String[] args) throws NoCarrotException { // declare
   eatCarrot();  
}
public static void main(String[] args) {
    try {
        eatCarrot();  
    } catch (NoCarrotException e) { // handle
        System.out.println(e);
    }
}

Fikir versək görərik ki, əslində eatCarrot() metodunda exception baş vermir, sadəcə NoCarrotException declare olunub. Elə bu kifayət edir ki, bu metodu hər hansı bir metodda çağırdıqda compiler handle və ya declare tələb etsin.

Metodun throws bölməsində ancaq java.lang.Throwable classından törəmiş classlar yazıla bilər.

Diqqət etməli olduğumuz daha bir vacib qayda var. Əgər hər hansı bir metodda checked exception fırladılmır və ya declare olunmursa, həmin metodu digər metod daxilində çağırdıqda həmin checked exception’u  handle etmək olmaz, çünki “try blokunda belə bir exception baş vermir” xətası verəcək və compile olunmayacaq. Amma declare etmək mümkündür. Nümunə üzərindən baxaq:

public void bad() {
    try {
        eatCarrot();
    } catch (NoCarrotException ex) {   // DOES NOT COMPILE
        System.out.println(ex);
    }
}

public void good() throws NoCarrotException {
    eatCarrot();
}

private static void eatCarrot() {}

eatCarrot() metodunda checked exception baş vermədiyindən compiler başa düşür ki, bad() metodunda heç bir halda catch blokuna çatmaq (reach) mümkün deyil və ona görə də xəta verir. Amma good() metodu istənilən exceptionu declare etməkdə sərbəstdir.

bad() metodunun catch blokunda NoCarrotException`u Exception və ya RuntimeException ilə əvəz etsək kod compile olunacaqdır.

 

[topics lang=az]

 

About the author

Mushfiq Mammadov

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.