Comment embellir les classes d’exception

Author:


Download

class MesExceptions extends Exception {
  private int x;
 
  public MesExceptions() {
  }
 
  public MesExceptions(String msg) {
    super(msg);
  }
 
  public MesExceptions(String msg, int x) {
    super(msg);
    this.x = x;
  }
 
  public int val() {
    return x;
  }
 
  public String getMessage() {
    return "Detail de l'exception: " + x + " " + super.getMessage();
  }
}
 
public class PersonnaliserException {
 
  public static void f() throws MesExceptions {
    System.out.println("Jeter l'exception � partir de  f()");
    throw new MesExceptions(); // Appel du constructeur sans argument
  }
 
  public static void g() throws MesExceptions {
    System.out.println("Jeter l'exception � partir de  g()"); // Appel du constructeur avec 1 seul argument
    throw new MesExceptions("Originated in g()");
  }
 
  public static void h() throws MesExceptions {
    System.out.println("Jeter l'exception � partir de  h()");
    throw new MesExceptions("Originated in h()", 47); // Appel du constructeur avec 2 arguments
  }
 
  public static void main(String[] args) {
    try {
      f();
    } catch (MesExceptions e) {
      e.printStackTrace();
    }
    try {
      g();
    } catch (MesExceptions e) {
      e.printStackTrace();
    }
    try {
      h();
    } catch (MesExceptions e) {
      e.printStackTrace();
      System.err.println("e.val() = " + e.val());
    }
  }
}