Ολοκληρωμένο παράδειγμα εξαιρέσεων


class BadArgException extends Throwable {
    public BadArgException() {}
    public BadArgException(String msg) {
        super(msg);
    }
}

class ExceptionTest {

    /** Verify that the args table is not empty.
     * @throws BadArgException if the table is empty.
     */
    static void verifyArgs(String args[]) throws BadArgException {
        if (args.length == 0)
            throw new BadArgException("Empty table");
    }

    /** Output the passed arguments.
     * @return 1 if the argument array is non-empty, 0 on error.
     */
    static int processArgs(String args[]) {
        try {
            int i;

            verifyArgs(args);
            for (i = 0; i < args.length; i++)
                System.out.print(args[i] + " ");
            System.out.println();
        } catch (BadArgException e) {
            System.err.println("Bad argument " + e);
            return 1;
        } finally {
            System.out.println("Argument processing done");
        }
        return 0;
    }

    static public void main(String[] args) {
        String[] args2 = {"Hello"};

        int exitCode = processArgs(args);

        System.out.println("Program termination");
        System.exit(exitCode);
    }
}