Exception Nedir?
Çalışma zamanında oluşan beklenmedik durumlardır. Java'da exception'lar nesne olarak temsil edilir ve fırlatılır/yakalanır.
try-catch-finally
try {
int sonuc = 10 / sayi;
System.out.println("Sonuç: " + sonuc);
} catch (ArithmeticException e) {
System.err.println("Sıfıra bölme hatası: " + e.getMessage());
} catch (Exception e) {
System.err.println("Beklenmedik hata: " + e.getMessage());
} finally {
System.out.println("Her durumda çalışır");
}Checked vs Unchecked
- Checked: Derleme zamanında kontrol edilir. IOException, SQLException. try-catch zorunlu.
- Unchecked: Çalışma zamanında. NullPointerException, ArrayIndexOutOfBoundsException.
Custom Exception
public class YetersizBakiyeException extends RuntimeException {
private double miktar;
public YetersizBakiyeException(double miktar) {
super("Yetersiz bakiye. İstenen: " + miktar);
this.miktar = miktar;
}
}
// Kullanım
if (bakiye < miktar) throw new YetersizBakiyeException(miktar);