Java asoslari 5-qism

08.06.2026 | Muallif: Jaxongir a.k.a | Kategoriya: Java tili | 22 daqiqa o'qish

6. Error Handling Basics

Error handling - dasturda xatolik bo‘lganda uni nazorat qilish mexanizmi.

Real dasturda xato doim bo‘ladi:

  • Fayl topilmaydi

  • Internet uziladi

  • Database ishlamay qoladi

  • User noto‘g‘ri input beradi

  • Null qiymat keladi

  • Raqam o‘rniga matn kiritiladi

Java’da bunday holatlar Exception orqali boshqariladi.

Roadmapdagi Beginner bo‘limida bu qism quyidagilarni o‘z ichiga oladi: exceptions hierarchy,try/catch/finally, checked vs unchecked exceptions, throw & throws.


6.1. Exception nima?

Exception - dastur ishlayotgan paytda yuz beradigan xatolik.

Masalan:

int result = 10 / 0;
System.out.println(result);

Bu kod xato beradi:

ArithmeticException: / by zero

Chunki sonni 0 ga bo‘lib bo‘lmaydi.

Yana misol:

String name = null;
System.out.println(name.length());

Bu xato beradi:

NullPointerException

Chunki null object emas. Unda length() methodi yo‘q.


6.2. Compile-time error va runtime error

Java’da xatolarni ikki katta turga ajratish mumkin.

Compile-time error

Kod compile bo‘lmaydi.

int age = "Ali";

Bu xato. Chunki int ichiga String berilyapti.

Compiler bu kodni ishga tushirishga ham ruxsat bermaydi.

Runtime error

Kod compile bo‘ladi, lekin ishlayotgan paytda yiqiladi.

int a = 10;
int b = 0;

System.out.println(a / b);

Bu compile bo‘ladi. Lekin ishlaganda xato beradi:

ArithmeticException

Exception asosan runtime paytdagi xatolar bilan bog‘liq.


6.3. Exception hierarchy

Java’da exception’lar class ko‘rinishida qurilgan.

Soddalashtirilgan ko‘rinish:

Throwable
├── Error
└── Exception
    ├── Checked Exception
    └── RuntimeException
        └── Unchecked Exception

Muhim qismlar:

Type

Ma’nosi

Throwable

barcha xato/exception’larning eng yuqori parent class’i

Error

odatda dasturchi ushlamaydi, JVM/system muammolari

Exception

dastur darajasidagi xatolar

RuntimeException

runtime paytda chiqadigan unchecked exceptionlar


6.4. Error va Exception farqi

Error

Error odatda jiddiy system/JVM muammosi.

Masalan:

OutOfMemoryError
StackOverflowError

Bularni odatda try/catch bilan ushlab, davom etish yaxshi amaliyot emas.

Masalan:

public class Main {
    public static void main(String[] args) {
        main(args);
    }
}

Bu cheksiz recursion qiladi va oxirida:

StackOverflowError

chiqadi.


Exception

Exception - dasturda yuz berishi mumkin bo‘lgan xato.

Masalan:

FileNotFoundException
IOException
SQLException
NumberFormatException
NullPointerException

Bularni ayrim holatda ushlash, log qilish, userga tushunarli xabar berish kerak.


6.5. try / catch

Agar xato chiqishi mumkin bo‘lgan kod bo‘lsa, uni try ichiga yozamiz.

try {
    int result = 10 / 0;
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Nolga bo‘lish mumkin emas");
}

Natija:

Nolga bo‘lish mumkin emas

Tushunish:

try   → xato chiqishi mumkin bo‘lgan kod
catch → xato chiqsa bajariladigan kod

6.6. try/catch qanday ishlaydi?

try {
    System.out.println("1");
    int result = 10 / 0;
    System.out.println("2");
} catch (ArithmeticException e) {
    System.out.println("Xato ushlandi");
}

System.out.println("3");

Natija:

1
Xato ushlandi
3

Nega 2 chiqmadi?

Chunki exception chiqqan joydan boshlab try ichidagi qolgan kod bajarilmaydi. Java darhol mos catch blokka o‘tadi.


6.7. Exception object

catch ichidagi e - exception object.

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println(e.getMessage());
}

Natija:

/ by zero

Ko‘p ishlatiladigan methodlar:

e.getMessage();      // xato xabari
e.printStackTrace(); // xato qayerda chiqqanini chiqaradi

Misol:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    e.printStackTrace();
}

printStackTrace() debug uchun foydali, lekin production’da odatda logging framework bilan log qilinadi.


6.8. Bir nechta catch

Bitta try uchun bir nechta catch yozish mumkin.

try {
    String text = null;
    System.out.println(text.length());
} catch (NullPointerException e) {
    System.out.println("Null qiymat bilan ishlash mumkin emas");
} catch (Exception e) {
    System.out.println("Boshqa xato yuz berdi");
}

Bu yerda NullPointerException chiqsa, birinchi catch ishlaydi.

Muhim qoida:

Specific exception yuqorida,
general exception pastda turishi kerak.

Noto‘g‘ri:

try {
    String text = null;
    System.out.println(text.length());
} catch (Exception e) {
    System.out.println("Boshqa xato");
} catch (NullPointerException e) {
    System.out.println("Null xato");
}

Bu compile error beradi. Chunki Exception hamma exceptionlarni ushlab qo‘yadi. Pastdagi NullPointerExceptionga navbat yetmaydi.

To‘g‘ri:

try {
    String text = null;
    System.out.println(text.length());
} catch (NullPointerException e) {
    System.out.println("Null xato");
} catch (Exception e) {
    System.out.println("Boshqa xato");
}

6.9. Multi-catch

Agar bir nechta exception uchun bir xil kod yozilsa:

try {
    String text = "abc";
    int number = Integer.parseInt(text);
    System.out.println(number);
} catch (NumberFormatException | NullPointerException e) {
    System.out.println("Input noto‘g‘ri");
}

Bu yerda NumberFormatException yoki NullPointerException chiqsa, bitta catch ishlaydi.


6.10. finally

finally - exception bo‘ladimi yo‘qmi, baribir bajariladigan blok.

try {
    int result = 10 / 2;
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Xato");
} finally {
    System.out.println("Finally ishladi");
}

Natija:

5
Finally ishladi

Agar exception chiqsa ham:

try {
    int result = 10 / 0;
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Xato");
} finally {
    System.out.println("Finally ishladi");
}

Natija:

Xato
Finally ishladi

6.11. finally nima uchun kerak?

finally odatda resurslarni yopish uchun ishlatiladi:

Faylni yopish
Database connection yopish
Network connection yopish
Lock bo‘shatish

Masalan soddalashtirilgan misol:

try {
    System.out.println("Fayl o‘qilyapti");
} catch (Exception e) {
    System.out.println("Xato yuz berdi");
} finally {
    System.out.println("Fayl yopildi");
}

Hozirgi Java’da resurslar uchun ko‘proq try-with-resources ishlatiladi. Lekin beginner bosqichida finally tushunchasini bilish kerak.


6.12. Checked va unchecked exception

Java’da exception ikki katta turga bo‘linadi:

Checked exception
Unchecked exception

Checked exception

Checked exception - compiler majburiy tekshirtiradigan exception.

Masalan:

import java.io.FileReader;

public class Main {
    public static void main(String[] args) {
        FileReader reader = new FileReader("data.txt");
    }
}

Bu compile bo‘lmaydi. Chunki FileReader FileNotFoundException chiqarishi mumkin.

Java aytadi:

Bu xatoni try/catch qil yoki throws bilan e’lon qil.

To‘g‘ri variant:

import java.io.FileReader;
import java.io.FileNotFoundException;

public class Main {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("data.txt");
        } catch (FileNotFoundException e) {
            System.out.println("Fayl topilmadi");
        }
    }
}

Checked exception misollari:

IOException
FileNotFoundException
SQLException
ClassNotFoundException

Unchecked exception

Unchecked exception - compiler majburlamaydigan exception.

Masalan:

int result = 10 / 0;

Compiler buni compile qiladi. Lekin runtime’da:

ArithmeticException

chiqadi.

Unchecked exceptionlar odatda RuntimeExceptiondan meros oladi.

Misollar:

NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
NumberFormatException
IllegalArgumentException

6.13. Checked vs unchecked farqi

Farq

Checked

Unchecked

Compiler majburlaydimi?

Ha

Yo‘q

Qachon chiqadi?

Tashqi resurslar bilan ishlaganda ko‘p

Kod mantiqi xatosida ko‘p

Misol

IOException

NullPointerException

Majburiy try/catch kerakmi?

Ha

Yo‘q

Oddiy tushuncha:

Checked    → Java oldindan: "bu xato bo‘lishi mumkin, hal qil" deydi
Unchecked  → Java majburlamaydi, lekin runtime’da yiqilishi mumkin

6.14. throw

throw - o‘zimiz exception chiqarish uchun ishlatiladi.

Masalan, yosh manfiy bo‘lmasligi kerak:

public class User {
    private int age;

    public void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age manfiy bo‘lishi mumkin emas");
        }

        this.age = age;
    }
}

Ishlatish:

User user = new User();
user.setAge(-5);

Natija:

IllegalArgumentException: Age manfiy bo‘lishi mumkin emas

Bu yaxshi, chunki noto‘g‘ri qiymat object ichiga kirib ketmaydi.


6.15. throw qachon ishlatiladi?

throw quyidagi holatlarda foydali:

Noto‘g‘ri argument kelganda
Business rule buzilganda
Kerakli ma’lumot topilmaganda
Dastur davom etishi xavfli bo‘lganda

Masalan:

public void withdraw(double amount) {
    if (amount <= 0) {
        throw new IllegalArgumentException("Amount musbat bo‘lishi kerak");
    }

    System.out.println("Pul yechildi: " + amount);
}

6.16. throws

throws - method exception chiqarishi mumkinligini e’lon qiladi.

Masalan checked exception bilan:

import java.io.FileReader;
import java.io.FileNotFoundException;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        FileReader reader = new FileReader("data.txt");
    }
}

Bu yerda:

throws FileNotFoundException

degani:

Bu method FileNotFoundException chiqarishi mumkin.
Uni chaqirgan joy hal qilsin.

6.17. throw va throws farqi

Keyword

Vazifasi

throw

Exceptionni hozir chiqaradi

throws

Method exception chiqarishi mumkinligini bildiradi

Misol:

public void checkAge(int age) {
    if (age < 18) {
        throw new IllegalArgumentException("Yosh yetmaydi");
    }
}

Bu yerda throw ishlatildi.

public void readFile() throws IOException {
    // file o‘qish
}

Bu yerda throws ishlatildi.

Qisqa:

throw  → action
throws → declaration

6.18. Custom exception

O‘zimizning exception class yaratishimiz mumkin.

Masalan:

public class NotEnoughBalanceException extends RuntimeException {
    public NotEnoughBalanceException(String message) {
        super(message);
    }
}

Ishlatish:

public class BankAccount {
    private double balance;

    public BankAccount(double balance) {
        this.balance = balance;
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            throw new NotEnoughBalanceException("Balans yetarli emas");
        }

        balance -= amount;
    }
}

Main:

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(100);

        account.withdraw(150);
    }
}

Natija:

NotEnoughBalanceException: Balans yetarli emas

Bu real loyihalarda juda foydali. Chunki exception nomidan ham xato turi tushunarli bo‘ladi.


6.19. Exceptionni yutib yubormaslik

Yomon amaliyot:

try {
    int result = 10 / 0;
} catch (Exception e) {
}

Bu juda yomon. Chunki xato bo‘ldi, lekin hech narsa qilinmadi.

Kamida log yoki xabar bo‘lishi kerak:

try {
    int result = 10 / 0;
} catch (Exception e) {
    System.out.println("Xato: " + e.getMessage());
}

Real projectlarda:

log.error("Failed to calculate result", e);

ko‘rinishida log qilinadi.


6.20. Har joyda try/catch yozish ham yomon

Yana bir yomon amaliyot:

try {
    try {
        try {
            // code
        } catch (Exception e) {
        }
    } catch (Exception e) {
    }
} catch (Exception e) {
}

Kod juda chalkash bo‘ladi.

Yaxshi yondashuv:

Exceptionni kerakli darajada ushla
Pastki methodda faqat ma’no bo‘lsa ushla
Aks holda yuqoriga throw qil
Controller/global handler darajasida userga javob qaytar

Spring Boot’da odatda @ControllerAdvice orqali global exception handling qilinadi. Bu keyingi bosqichlarda chuqur o‘rganiladi.


6.21. NullPointerException

Java’da eng ko‘p uchraydigan exceptionlardan biri.

String name = null;
System.out.println(name.length());

Xato:

NullPointerException

Sabab:

name null, ya’ni object yo‘q.
Object yo‘q bo‘lsa, method chaqirib bo‘lmaydi.

Oldini olish:

String name = null;

if (name != null) {
    System.out.println(name.length());
}

Yoki String solishtirishda xavfsizroq usul:

String role = null;

if ("ADMIN".equals(role)) {
    System.out.println("Admin user");
}

Bu xato bermaydi.

Lekin bu xato berishi mumkin:

if (role.equals("ADMIN")) {
    System.out.println("Admin user");
}

Chunki role null bo‘lishi mumkin.


6.22. NumberFormatException

Matndan son yasashda xato bo‘lishi mumkin.

String text = "123";
int number = Integer.parseInt(text);

System.out.println(number);

Natija:

123

Lekin:

String text = "abc";
int number = Integer.parseInt(text);

Xato:

NumberFormatException

To‘g‘ri ishlov berish:

String text = "abc";

try {
    int number = Integer.parseInt(text);
    System.out.println(number);
} catch (NumberFormatException e) {
    System.out.println("Raqam noto‘g‘ri formatda");
}

6.23. ArrayIndexOutOfBoundsException

Array chegarasidan chiqilganda:

int[] numbers = {10, 20, 30};

System.out.println(numbers[3]);

Xato:

ArrayIndexOutOfBoundsException

To‘g‘ri:

int[] numbers = {10, 20, 30};

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

6.24. Amaliy misol: user input parse qilish

public class Main {
    public static void main(String[] args) {
        String input = "25";

        try {
            int age = Integer.parseInt(input);

            if (age < 0) {
                throw new IllegalArgumentException("Yosh manfiy bo‘lishi mumkin emas");
            }

            System.out.println("Age: " + age);
        } catch (NumberFormatException e) {
            System.out.println("Yosh faqat raqam bo‘lishi kerak");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Agar:

String input = "25";

Natija:

Age: 25

Agar:

String input = "abc";

Natija:

Yosh faqat raqam bo‘lishi kerak

Agar:

String input = "-5";

Natija:

Yosh manfiy bo‘lishi mumkin emas

6.25. Amaliy misol: bank account

public class BankAccount {
    private double balance;

    public BankAccount(double balance) {
        if (balance < 0) {
            throw new IllegalArgumentException("Boshlang‘ich balans manfiy bo‘lishi mumkin emas");
        }

        this.balance = balance;
    }

    public void withdraw(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Yechiladigan summa musbat bo‘lishi kerak");
        }

        if (amount > balance) {
            throw new IllegalArgumentException("Balans yetarli emas");
        }

        balance -= amount;
    }

    public double getBalance() {
        return balance;
    }
}

Ishlatish:

public class Main {
    public static void main(String[] args) {
        try {
            BankAccount account = new BankAccount(100);

            account.withdraw(30);

            System.out.println("Balance: " + account.getBalance());
        } catch (IllegalArgumentException e) {
            System.out.println("Xato: " + e.getMessage());
        }
    }
}

Natija:

Balance: 70.0

Agar:

account.withdraw(150);

Natija:

Xato: Balans yetarli emas

6.26. Beginner xatolar

Xato 1: Hamma joyda catch (Exception e) yozish

Yomon:

try {
    int number = Integer.parseInt("abc");
} catch (Exception e) {
    System.out.println("Xato");
}

Yaxshi:

try {
    int number = Integer.parseInt("abc");
} catch (NumberFormatException e) {
    System.out.println("Raqam formati noto‘g‘ri");
}

Aniq exception ushlansa, xato sababi tushunarli bo‘ladi.


Xato 2: Exceptionni yutib yuborish

Yomon:

try {
    int result = 10 / 0;
} catch (Exception e) {
}

Yaxshi:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Nolga bo‘lish mumkin emas");
}

Xato 3: finally ichida return yozish

Yomon amaliyot:

public int test() {
    try {
        return 1;
    } finally {
        return 2;
    }
}

Bu chalkash va xavfli. finallydagi return oldingi returnni bosib ketishi mumkin.

Yaxshi:

public int test() {
    try {
        return 1;
    } finally {
        System.out.println("Cleanup");
    }
}

Xato 4: Exception bilan normal logic qilish

Yomon:

try {
    int value = numbers[10];
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Element yo‘q");
}

Yaxshi:

if (index >= 0 && index < numbers.length) {
    int value = numbers[index];
} else {
    System.out.println("Element yo‘q");
}

Exception oddiy if o‘rniga ishlatilmasligi kerak.


6.27. Qachon try/catch, qachon throw?

Holat

Nima qilamiz?

Xatoni shu joyda hal qila olsak

try/catch

Xatoni shu joyda hal qila olmasak

throw yoki throws

Input noto‘g‘ri bo‘lsa

throw new IllegalArgumentException(...)

Tashqi resurs bilan ishlasak

checked exceptionni handle qilamiz

Userga tushunarli javob kerak bo‘lsa

yuqori layerda ushlaymiz


6.28. Kichik mashq

Vazifa

Product class yoz:

field:
- name
- price

constructor:
- name null yoki bo‘sh bo‘lsa exception chiqarsin
- price <= 0 bo‘lsa exception chiqarsin

method:
- getInfo() product haqida matn qaytarsin

Yechim:

public class Product {
    private String name;
    private double price;

    public Product(String name, double price) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("Product name bo‘sh bo‘lishi mumkin emas");
        }

        if (price <= 0) {
            throw new IllegalArgumentException("Product price musbat bo‘lishi kerak");
        }

        this.name = name;
        this.price = price;
    }

    public String getInfo() {
        return name + " = $" + price;
    }
}

Ishlatish:

public class Main {
    public static void main(String[] args) {
        try {
            Product product = new Product("Laptop", 1000);
            System.out.println(product.getInfo());
        } catch (IllegalArgumentException e) {
            System.out.println("Xato: " + e.getMessage());
        }
    }
}

Natija:

Laptop = $1000.0

Agar:

Product product = new Product("", 1000);

Natija:

Xato: Product name bo‘sh bo‘lishi mumkin emas

6.29. Qisqa xulosa

Error handling Java’da xatolarni nazorat qilish uchun kerak:

Exception       → runtime xato
try             → xato chiqishi mumkin bo‘lgan kod
catch           → xatoni ushlash
finally         → baribir ishlaydigan cleanup blok
checked         → compiler majburlaydi
unchecked       → compiler majburlamaydi
throw           → exception chiqarish
throws          → method exception chiqarishi mumkinligini e’lon qilish
custom exception→ o‘zimizning xato turimiz

Eng muhim fikr:

Exception - dasturni yiqitish uchun emas, xatoni nazoratli boshqarish uchun kerak.

Beginner bosqichi shu yerda yakunlanadi. Keyingi katta bo‘lim: Junior → OOP Deep Dive - interfaces, abstract classes, polymorphism, composition over inheritance, encapsulation patterns, inner classes, anonymous classes, enums.