Junior
Çağırış yığını içində yuxarıda istisnaları necə atardınız?
sobes.tech Süni İntellekt
AI-dan cavab
Açar söz throw istifadə edirəm, istisnanı yenidən atmaq və ya yeni istisna yaratmaq üçün.
public void method1() throws CustomException {
try {
// Hər hansı bir kod, AnotherException ata bilər
method2();
} catch (AnotherException e) {
// AnotherException-u tuturuq
// Bunu CustomException-ə bağlayıb yuxarı atırıq
throw new CustomException("Method2-də xəta: " + e.getMessage(), e);
}
}
public void method2() throws AnotherException {
// Hər hansı bir kod, istisna ata bilər
throw new AnotherException("Method2-də nəsə səhv getdi");
}
class CustomException extends Exception {
public CustomException(String message, Throwable cause) {
super(message, cause);
}
}
class AnotherException extends Exception {
public AnotherException(String message) {
super(message);
}
}
Yaxud, sadəcə tutulan istisnanı yuxarı atmaq istəyirsinizsə, yeni yaratmadan:
public void methodA() throws SomeException {
try {
methodB();
} catch (SomeException e) {
// Qeyd və ya digər əməliyyatlar
// Eyni istisnanı yuxarı atırıq
throw e;
}
}
public void methodB() throws SomeException {
// SomeException ata bilər
throw new SomeException("MethodB-də xəta");
}
class SomeException extends Exception {
public SomeException(String message) {
super(message);
}
}