Junior
Çağrı yığını içinde daha yukarıda istisnaları nasıl atardınız?
sobes.tech yapay zeka
AI'dan gelen yanıt
Anahtar kelime throw kullanıyorum, yeniden atmak veya yeni bir istisna oluşturmak için.
public void method1() throws CustomException {
try {
// Bir şeyler yapıyor, AnotherException atabilir
method2();
} catch (AnotherException e) {
// AnotherException yakalanır
// CustomException içine sarılır ve yukarı atılır
throw new CustomException("Method2'de hata: " + e.getMessage(), e);
}
}
public void method2() throws AnotherException {
// Bir şeyler yapıyor, istisna atabilir
throw new AnotherException("Method2'de bir şeyler ters gitti");
}
class CustomException extends Exception {
public CustomException(String message, Throwable cause) {
super(message, cause);
}
}
class AnotherException extends Exception {
public AnotherException(String message) {
super(message);
}
}
Veya, sadece yakalanan istisnayı yeniden atmak istiyorsanız, yeni oluşturmadan:
public void methodA() throws SomeException {
try {
methodB();
} catch (SomeException e) {
// Günlük kaydı veya diğer işlemler
// Aynı istisnayı yukarıya atıyoruz
throw e;
}
}
public void methodB() throws SomeException {
// SomeException atabilir
throw new SomeException("MethodB'de hata");
}
class SomeException extends Exception {
public SomeException(String message) {
super(message);
}
}