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.
Bu qism quyidagilarni o‘z ichiga oladi: exceptions hierarchy,try/catch/finally, checked vs unchecked exceptions, throw & throws.
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 zeroChunki sonni 0 ga bo‘lib bo‘lmaydi.
Yana misol:
String name = null;
System.out.println(name.length());Bu xato beradi:
NullPointerExceptionChunki null object emas. Unda length() methodi yo‘q.
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:
ArithmeticExceptionException asosan runtime paytdagi xatolar bilan bog‘liq.
3. Exception hierarchy
Java’da exception’lar class ko‘rinishida qurilgan.
Soddalashtirilgan ko‘rinish:
Throwable
├── Error
└── Exception
├── Checked Exception
└── RuntimeException
└── Unchecked ExceptionMuhim qismlar:
Type | Ma’nosi |
|---|---|
| barcha xato/exception’larning eng yuqori parent class’i |
| odatda dasturchi ushlamaydi, JVM/system muammolari |
| dastur darajasidagi xatolar |
| runtime paytda chiqadigan unchecked exceptionlar |
4. Error va Exception farqi
Error
Error odatda jiddiy system/JVM muammosi.
Masalan:
OutOfMemoryError
StackOverflowErrorBularni 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:
StackOverflowErrorchiqadi.
Exception
Exception - dasturda yuz berishi mumkin bo‘lgan xato.
Masalan:
FileNotFoundException
IOException
SQLException
NumberFormatException
NullPointerExceptionBularni ayrim holatda ushlash, log qilish, userga tushunarli xabar berish kerak.
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 emasTushunish:
try → xato chiqishi mumkin bo‘lgan kod
catch → xato chiqsa bajariladigan kod6. 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
3Nega 2 chiqmadi?
Chunki exception chiqqan joydan boshlab try ichidagi qolgan kod bajarilmaydi. Java darhol mos catch blokka o‘tadi.
7. Exception object
catch ichidagi e - exception object.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}Natija:
/ by zeroKo‘p ishlatiladigan methodlar:
e.getMessage(); // xato xabari
e.printStackTrace(); // xato qayerda chiqqanini chiqaradiMisol:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
e.printStackTrace();
}printStackTrace() debug uchun foydali, lekin production’da odatda logging framework bilan log qilinadi.
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");
}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.
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 ishladiAgar 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 ishladi11. finally nima uchun kerak?
finally odatda resurslarni yopish uchun ishlatiladi:
Faylni yopish
Database connection yopish
Network connection yopish
Lock bo‘shatishMasalan 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 boshlang'ich bosqichida finally tushunchasini bilish kerak.
12. Checked va unchecked exception
Java’da exception ikki katta turga bo‘linadi:
Checked exception
Unchecked exceptionChecked 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
ClassNotFoundExceptionUnchecked exception
Unchecked exception - compiler majburlamaydigan exception.
Masalan:
int result = 10 / 0;Compiler buni compile qiladi. Lekin runtime’da:
ArithmeticExceptionchiqadi.
Unchecked exceptionlar odatda RuntimeExceptiondan meros oladi.
Misollar:
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
NumberFormatException
IllegalArgumentException13. 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 |
|
|
Majburiy | Ha | Yo‘q |
Oddiy tushuncha:
Checked → Java oldindan: "bu xato bo‘lishi mumkin, hal qil" deydi
Unchecked → Java majburlamaydi, lekin runtime’da yiqilishi mumkin14. 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 emasBu yaxshi, chunki noto‘g‘ri qiymat object ichiga kirib ketmaydi.
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‘lgandaMasalan:
public void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Amount musbat bo‘lishi kerak");
}
System.out.println("Pul yechildi: " + amount);
}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 FileNotFoundExceptiondegani:
Bu method FileNotFoundException chiqarishi mumkin.
Uni chaqirgan joy hal qilsin.17. throw va throws farqi
Keyword | Vazifasi |
|---|---|
| Exceptionni hozir chiqaradi |
| 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 → declaration18. 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 emasBu real loyihalarda juda foydali. Chunki exception nomidan ham xato turi tushunarli bo‘ladi.
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.
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 qaytarSpring Boot’da odatda @ControllerAdvice orqali global exception handling qilinadi. Bu keyingi bosqichlarda chuqur o‘rganiladi.
21. NullPointerException
Java’da eng ko‘p uchraydigan exceptionlardan biri.
String name = null;
System.out.println(name.length());Xato:
NullPointerExceptionSabab:
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.
22. NumberFormatException
Matndan son yasashda xato bo‘lishi mumkin.
String text = "123";
int number = Integer.parseInt(text);
System.out.println(number);Natija:
123Lekin:
String text = "abc";
int number = Integer.parseInt(text);Xato:
NumberFormatExceptionTo‘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");
}23. ArrayIndexOutOfBoundsException
Array chegarasidan chiqilganda:
int[] numbers = {10, 20, 30};
System.out.println(numbers[3]);Xato:
ArrayIndexOutOfBoundsExceptionTo‘g‘ri:
int[] numbers = {10, 20, 30};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}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: 25Agar:
String input = "abc";Natija:
Yosh faqat raqam bo‘lishi kerakAgar:
String input = "-5";Natija:
Yosh manfiy bo‘lishi mumkin emas25. 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.0Agar:
account.withdraw(150);Natija:
Xato: Balans yetarli emas26. Boshlang'ichlar xatolari
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.
27. Qachon try/catch, qachon throw?
Holat | Nima qilamiz? |
|---|---|
Xatoni shu joyda hal qila olsak |
|
Xatoni shu joyda hal qila olmasak |
|
Input noto‘g‘ri bo‘lsa |
|
Tashqi resurs bilan ishlasak | checked exceptionni handle qilamiz |
Userga tushunarli javob kerak bo‘lsa | yuqori layerda ushlaymiz |
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 qaytarsinYechim:
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.0Agar:
Product product = new Product("", 1000);Natija:
Xato: Product name bo‘sh bo‘lishi mumkin emas29. 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 turimizEng muhim fikr:
Exception - dasturni yiqitish uchun emas, xatoni nazoratli boshqarish uchun kerak.