Java exceptions

From wikinotes

Documentation

exception class docs https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Exception.html

Basics

try {
    // do something
} catch(Exception ex){
    // handle this exception type
} finally {
    // after success/fail handled, run this
}

repeat exception

try {
    // do something
} catch (Exception ex) {
    throw ex;  // re-throws identical exception
}

Declaring Exceptions

Java requires all exceptions (except RuntimeErrors) be either declared, or handled by the method that handles them.

Example

import java.io.IOException;


class A
{
    /** declares exception
    */
    void throws_exception() 
        throws java.io.IOException      // <-- callers must handle this exception
    {
        throw java.io.IOException("blah");
    }

    /** handles exception
    */
    void main()
    {
        try
        {
            this.throws_exception()
        } catch (java.io.IOException e)
            pass;
        }
    }
}


Custom Exceptions

It is considered a good practice to have a base-class for all of a package's exceptions. It makes your code more approachable to other devs, and also makes it simpler to refactor.

Define Custom Exception


public class QuickRefException extends Exception       // must be public to access outside of package
{
    private static final long serialVersionUID = 1L;   // version up when implementation changes

    public QuickRefException(String message)           // must be public to use outside of package
    {
        super(message);
    }
}

Throw Custom Exception


void throw_exception() throws QuickRefException
{
throw new QuickRefException("my reason");
}


Common Exceptions

java.lang.IllegalArgumentException   // bad arguments
java.lang.IndexOutOfBoundsException  // object (array, dict, ...) out of range
java.lang.Exception                  // normal exceptions
java.lang.RuntimeException           // runtime-exceptions do not need to be caught, or declared with 'throws'

java.nio.file.AccessDeniedException  // filesystem object inaccessible