Using Exception in Java

  1. Only use exception when there is exception, do not substitute the control flow.

    if (!stack.isEmpty()) stack.pop();
    
    try {
        s.pop();
    } catch(EmptyStackException e) {
        
    }
    

    Use an exception to tell code not to do so is a bad idea.

    And caching exception takes more time that calling isEmpty() in this example.

    Exception is design to handle exception so JVM has no optimize here, that's why it's slow.

    Same example can be found in Interator in java, where there is hasNext

  2. Do not over break the exception

    Stack stack;
    PrintStream out;
    for (int i = 0; i < 100; i++) {
        try {
            n = stack.pop();
        } catch (EmptyStackException e) {
            // stack was empty
        }
        try {
            out.wirteInt(n);
        } catch (IOException e) {
            // problem writing to file
        }
        
    }
    

    This will cause too much useless code.

    Code can be more clear and it separate the normal code and exception handing:

    try {
        for (int i = 0; i < 100; i++) {
            n = s.pop();
            out.wirteInt(n);
        }
    } catch (IOException e) {
        // problem writing to file
    } catch (EmptyStackException e) {
        // stack was empty
    }
    
  3. Use exception hierarchy

    Use more specific exception or create your own exception(But use standard exception first).

  4. Throw exception earlier and pass them.

  5. Use checked exception for recoverable situation, use run time exception for programming error.