2 Nisan 2018 Pazartesi

RuntimeException Sınıfı

Giriş
catch() ile yakalanmak zorunda olmayan (unchecked exception) exception türüdür.
Örneğin NoSuchElementException

Java'dan önce exception handling için iki tane yöntem vardı. Açıklaması şöyle.
Some programming languages and their implementations react to such errors by peremptorily terminating the program; other programming languages allow an implementation to react in an arbitrary or unpredictable way. Neither of these approaches is compatible with the design goals of the Java SE platform: to provide portability and robustness.
İlk yönten exception olunca uygulamayı kapatıyordu. İkinci yöntem ise uygulamananın çalışmasına müsade ediyor ancak tutarlı bir davranış sergileyemiyordu.
Java bu iki yöntemden farklı olarak try-catch blokları kullanılarak exception handling'i düzgün bir yapıya oturtmuştur.

Constructor İçinde Exception
C++ dilinin aksine constructor içinde exception fırlatılabilir.

Örnek
Şöyle yaparız.
public class Product {

  private String name;

  public Product(String name) {
    super();
    //DO NOT ALLOW OBJECT CREATION IF name is null or empty
    if(name != null && !name.isEmpty()) {
      this.name = name;
    } else {
      throw new IllegalArgumentException("name should not be null or Empty ");
    }
  }

}

Hiç yorum yok:

Yorum Gönder