Differenze tra le versioni di "Programmazione:Java/Logging"

Da WikiSitech.
Vai alla navigazioneVai alla ricerca
 
Riga 54: Riga 54:
 
}</code>
 
}</code>
 
|-  
 
|-  
'''Bad Practice (case 3)'''
+
|'''Bad Practice (case 3)'''
 
<code java>
 
<code java>
 
public class A {
 
public class A {

Versione delle 13:24, 31 ott 2007

Logging

Per loggare avere un log 'utilizzabile' è necessario che l'eccezione venga loggata al massimo due volte:

  • Chi intercetta l'eccezione originale deve loggare senza lo stacktrace e trasformarla in un eccezione applicativa
  • Chi intercetta l'eccezione applicativa deve loggare l'eccezione completa di stacktrace

tutti gli altri punti in cui passa l'eccezione devono propagarla senza intercettarla e riloggarla nuovamente

Bad Practice (case 1) public class A {

  public static void f() throws AppException {
     try {
        // Do something
     } catch(Throwable t) {
        throw new AppException(t);
     }
  }

}

public class B {

  void f1() {
     try {
        A.f();
     } catch(AppException t) {
     }      
  }

}

Bad Practice (case 2) public class A {

  public static void f() throws AppException {
     try {
        // Do something
     } catch(Throwable t) {
        t.printStackTrace();
        throw new AppException(t);
     }
  }

}

public class B {

  void f1() {
     try {
        A.f();
     } catch(AppException t) {
        t.printStackTrace();
     }      
  }

}

Bad Practice (case 3)

public class A {

  public static void f() throws TExcept {
     try {
        // Do something
     } catch(Throwable t) {
        System.out.println(t.getMessage();
        throw new TExcept(t);
     }
  }

}

public class B {

  void f1() {
     try {
        A.f();
     } catch(TExcept t) {
        System.out.println(t.getMessage();
     }      
  }

}