J'ai résumé les règles que je pense personnellement (ou sont largement suivies) d'essayer, d'attraper et enfin. Si vous avez un autre contenu à protéger, veuillez commenter.
enfin est toujours exécuté.
try {
    return 1;
} finally {
    return 2;
}
La génération d'exceptions n'est pas gratuite.
pour
int sum = 0;
for (int i = 0; i < 99900000; i++) {
    try {
        sum += i;
    } catch (Exception ex) {
    }
}
pour l'extérieur
int sum = 0;
try {
    for (int i = 0; i < 99900000; i++) {
        sum += i;
    }
} catch (Exception ex) {
}
En raison de la mesure du temps, il y a une différence de performance de 21%. pour: "1312" extérieur: "1042"
Si vous ne désactivez pas JIT (Just In Time), le code sera optimisé et il n'y aura aucune différence. Option invalide JIT: -Djava.compiler = aucun
L'objet avec l'exception peut continuer à être utilisé.
échantillon
private static class A {
taille maximale int finale privée= 10;
taille actuelle de private int= 0;
    String[] values = new String[20];
    public void add(String val) throws Exception {
La taille actuelle++;
        if (La taille actuelle>Taille maximum) {
            throw new Exception("Dépassé la taille maximale");
        }
        values[La taille actuelle- 1] = val;
    }
}
Code en question
La taille actuelle++;
if (La taille actuelle>Taille maximum) {
    throw new Exception("Dépassé la taille maximale");
}
values [taille actuelle], cela peut être illégal.Les processus qui peuvent être contrôlés par un traitement normal ne doivent pas être traités par exception.
Contrôlez le processus avec des exceptions
private static void showWithEx(String[] src) {
    try {
        int i = 0;
        while (true) {
            String s = src[i++];
        }
    } catch (ArrayIndexOutOfBoundsException ex) {
    }
}
Après rénovation
private static void show(String[] src) {
    int i = 0;
    while (i < src.length) {
        String s = src[i++];
    }
}
Mesure des coûts d'exception
python
public static void main(String[] args) {
    final int COUNT = 100000;
    String[] src = {"ab", "cd", "ef"};
    long start = 0L;
    
    start = System.currentTimeMillis();
    for (int i = 0; i < COUNT; i++) {
        showWithEx(src);
    }
    System.out.println(System.currentTimeMillis() - start);
    start = System.currentTimeMillis();
    for (int i = 0; i < COUNT; i++) {
        show(src);
    }
    System.out.println(System.currentTimeMillis() - start);
    start = System.currentTimeMillis();
    for (int i = 0 ; i < COUNT; i++ ) {
        Object o = new ArrayIndexOutOfBoundsException();
    }
    System.out.println(System.currentTimeMillis() - start);
}
production
0
156
63
Il est facile de mettre tout le traitement en un seul essai, ce qui est beau et simple à première vue, mais c'est en fait un piège.
Un énorme essai est NG
public static void main(String[] args) {
    try {
        //Abréviation
        String src;
   
        src = "123";
        int val1 = Integer.parseInt(src);
        src = "abc";
        int val2 = Integer.parseInt(src);
        //Abréviation
        src = null;
        src.getBytes();
    } catch (NumberFormatException ex) {
        System.out.println(ex.getMessage());
    } catch (NullPointerException ex ) {
        System.out.println(ex.getMessage());
    }
}
Il est NG d'attraper avec une classe d'exception supérieure (Throwable).
N'utilisez pas Catch_all
try {
    // Checked Exception
    File f = new File("n'existe pas");
    int b = new FileInputStream(f).read();
    // Runtime Exception
    Object o = null;
    o.getClass();
} catch (Throwable ex) {
    ex.printStackTrace();
}
Si catch, finalement lève une exception, le contenu de l'exception peut être masqué.
public static void main(String[] args) {
    try {
        m1();
    } catch (Exception ex) {
        System.out.println("In main : " + ex.getMessage());
    }
}
private static void m1() throws Exception {
    try {
        System.out.println("m1 : try");
        throw new Exception("First EX");
    } catch (Exception ex) {
        System.out.println("m1 : catch");
        throw new Exception("Second EX");
    } finally {
        System.out.println("m1 : finally");
        throw new Exception("Third EX");
    }
}
production
m1 : try
m1 : catch
m1 : finally
In main : Third EX.
La cause première est throw new Exception (" First EX ");
J'ai ramassé un throw new Exception (" Third EX ");.
J'ai attrapé une exception, mais "ne rien faire ou ne sortir que le journal" est un travail de dissimulation. Cela a un impact considérable sur la santé du programme.
Ignorer les exceptions
try {
    File f = new File("n'existe pas");
    int b = new FileInputStream(f).read();
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
Traitement approprié des exceptions

Recommended Posts