Java exception handling usage rules

Regulations for handling exceptions

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.

Don't return with try

finally is always executed.

try {
    return 1;
} finally {
    return 2;
}
  1. The return value is 2.
  2. try return may be overwritten by finally return.

try / catch out of loop

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

Return the object to a valid state before throwing an exception

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");
}
  1. I threw an exception, but the maximum size of this object remains maximum size + 1.
  2. If you execute values [current size], it may be illegal.

Don't control the process with exception handling

Processes that can be controlled by normal processing should not be processed by exception.

  1. Readability is reduced
  2. Exception handling is costly

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
  1. After the repair, it was 0 no matter how many times it was increased.
  2. It took 156 before the renovation
  3. new ArrayIndexOutOfBoundsException () is 63, so costs other than generation cannot be ignored.

Don't use a huge try

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.

  1. "Long code = there is a high possibility that an exception will occur", so it is difficult to debug where the exception occurred.
  2. A huge try has more catch clauses, and those logic relationships must be resolved.

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());
    }
}

Don't use Catch all

It is NG to catch with one upper exception class (Throwable).

  1. Only the same measures can be taken for various exceptions. Processing can be divided using if and instanceOf in catch, but ... stop ...
  2. Even if the program should be stopped, such as RuntimeException, it will be caught and will be suppressed without anyone knowing it.

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();
}

Don't hide exceptions

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"); .

Don't ignore exceptions

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

  1. Checked exceptions should be repaired programmatically
  2. For unrepairable exceptions, use throws to ask the caller to repair

bonus

(Regular) Exception class system

Ex-class.png

Exception class classification

Recommended Posts

Java exception handling usage rules
Java exception handling?
[Java] Exception handling
☾ Java / Exception handling
Java exception handling
Java exception handling
[Java] Practice of exception handling [Exception]
[Java] About try-catch exception handling
Exception handling techniques in Java
Exception handling
Exception handling Exception
[In-house study session] Java exception handling (2017/04/26)
Step-by-step understanding of Java exception handling
[For Java beginners] About exception handling
About exception handling
About exception handling
ruby exception handling
[Java] Exception instance
Ruby exception handling
Java (exception handling, threading, collection, file IO)
try-catch-finally exception handling How to use java
Questions in java exception handling throw and try-catch
Exception handling practice (ArithmeticException)
[Ruby] Exception handling basics
[java] throw an exception
Spring Boot exception handling
Regarding Java variable usage
[Java Silver] (Exception handling) About try-catch-finally and try-with-resource statements
Classes that require exception handling
Java basic learning content 7 (exception)
[Java] Mirage-Basic usage of SQL
Java's first exception handling (memories)
[Ruby] Exception handling in functions
[Java11] Stream Usage Summary -Basics-
(Learning memo) Java 2nd grade measures: Q4 main points (exception handling)
[Introduction to Java] About exception handling (try-catch-finally, checked exception, unchecked exception, throws, throw)
Leverage Either for individual exception handling in the Java Stream API
JCA (Java Cryptography Architecture) Usage Memo
Basic usage of java Optional Part 1
Handling of time zones using Java
[Rails] How to write exception handling?
Measuring instance memory usage in Java
[Note] Handling of Java decimal point
Unexpected exception when using Java DateTimeFormatter
[Java] What is Concurrent Modification Exception?
Exception handling with a fluid interface
[Java] Exception types and basic processing