Sobes.tech
Junior

Qanday qilib siz chaqirishlar stekida yuqoriroq xatoliklarni chiqarasiz?

sobes.tech AI

AIdan javob

Men throw kalit so'zidan foydalanaman, bu orqali istisnoni qayta yuborish yoki yangi istisno yaratish.

public void method1() throws CustomException {
    try {
        // Biror kod, u AnotherException chiqarishi mumkin
        method2();
    } catch (AnotherException e) {
        // AnotherException ni tutamiz
        // Uni CustomException ga o'rab, yuqoriga yuboramiz
        throw new CustomException("Method2 da xato: " + e.getMessage(), e);
    }
}

public void method2() throws AnotherException {
    // Biror kod, istisno chiqarishi mumkin
    throw new AnotherException("Method2 da nimadir noto'g'ri bo'ldi");
}

class CustomException extends Exception {
    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }
}

class AnotherException extends Exception {
    public AnotherException(String message) {
        super(message);
    }
}

Yoki, agar faqat ushlangan istisnoni yuqoriga yubormoqchi bo'lsangiz, yangi yaratmasdan:

public void methodA() throws SomeException {
    try {
        methodB();
    } catch (SomeException e) {
        // Log qilish yoki boshqa harakatlar
        // Shu istisnoni yuqoriga yuboramiz
        throw e;
    }
}

public void methodB() throws SomeException {
    // SomeException chiqarishi mumkin
    throw new SomeException("MethodB da xato");
}

class SomeException extends Exception {
    public SomeException(String message) {
        super(message);
    }
}