10k

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`
  1. 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
    }
  1. Use exception hierarchy

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

  2. Throw exception earlier and pass them.

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

Thoughts? Leave a comment