Here is a summary of the rules that I personally think (or are widely followed) of try, catch, and finally. If you have any other content to protect, please comment.
finally is always executed.
try {
    return 1;
} finally {
    return 2;
}
try return may be overwritten by finally return.Exception generation is not free.
in for
int sum = 0;
for (int i = 0; i < 99900000; i++) {
    try {
        sum += i;
    } catch (Exception ex) {
    }
}
for outside
int sum = 0;
try {
    for (int i = 0; i < 99900000; i++) {
        sum += i;
    }
} catch (Exception ex) {
}
As a result of measuring the time, there is a performance difference of 21%.
in for: 1312
outside: 1042
If you do not disable JIT (Just In Time), the code will be optimized and there will be no difference. JIT disabled option: -Djava.compiler = none
The object with the exception may continue to be used.
sample
private static class A {
private final int maximum size= 10;
private int current size= 0;
    String[] values = new String[20];
    public void add(String val) throws Exception {
Current size++;
        if (Current size>Maximum size) {
            throw new Exception("Exceeded the maximum size");
        }
        values[Current size- 1] = val;
    }
}
Code in question
Current size++;
if (Current size>Maximum size) {
    throw new Exception("Exceeded the maximum size");
}
maximum size + 1.values [current size], it may be illegal.Processes that can be controlled by normal processing should not be processed by exception.
Control the process with exceptions
private static void showWithEx(String[] src) {
    try {
        int i = 0;
        while (true) {
            String s = src[i++];
        }
    } catch (ArrayIndexOutOfBoundsException ex) {
    }
}
After renovation
private static void show(String[] src) {
    int i = 0;
    while (i < src.length) {
        String s = src[i++];
    }
}
Exception cost measurement
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);
}
output
0
156
63
It's easy to put all the processing into one try, which looks beautiful and simple at first glance, but it's actually a trap.
Huge try is NG
public static void main(String[] args) {
    try {
        //Abbreviation
        String src;
   
        src = "123";
        int val1 = Integer.parseInt(src);
        src = "abc";
        int val2 = Integer.parseInt(src);
        //Abbreviation
        src = null;
        src.getBytes();
    } catch (NumberFormatException ex) {
        System.out.println(ex.getMessage());
    } catch (NullPointerException ex ) {
        System.out.println(ex.getMessage());
    }
}
It is NG to catch with one upper exception class (Throwable).
Don't use Catch_all
try {
    // Checked Exception
    File f = new File("not exist");
    int b = new FileInputStream(f).read();
    // Runtime Exception
    Object o = null;
    o.getClass();
} catch (Throwable ex) {
    ex.printStackTrace();
}
If catch, finally throws an exception, the exception content may be hidden.
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");
    }
}
output
m1 : try
m1 : catch
m1 : finally
In main : Third EX.
The root cause is throw new Exception ("First EX"); 
I picked up throw new Exception ("Third EX"); .
I caught an exception, but "doing nothing or outputting only the log" is a cover-up. It has a great impact on the health of the program.
Ignore exceptions
try {
    File f = new File("not exist");
    int b = new FileInputStream(f).read();
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
Appropriate exception handling

Recommended Posts