How to Create Exception Classes in Java

The Java programming language takes an exceptions-based approach to handling error detection and handling in code. Rather than create a complex system of nested if-else statements to try to catch every possible error, all error catching can be organized into a series of "try-catch" statements at the end of a function. This allows error control to get out of the way of the program's actual flow and leads to more readable, easier-to-maintain code.

Instructions

    1

    Choose a parent class. Any subclass of java.lang.Exception can be used as the parent for a new exception class. However, for this example, you'll use the basic Exception class as a parent. Exception gives us all the basic necessities of an exception: it is throwable, it can print a stack trace, and allows a message to be retrieved about the nature of the exception.

    2

    Create a subclass that extends that parent class. This is the same as creating any other subclass in Java. For good code readability, it is standard to always end the class name with the word "Exception". For this example, you'll build an exception for handling bad user input, called, simply enough, BadUserInputException.

    public class BadUserInputException extends Exception

    This code alone actually gives you all you need to immediately starting throwing and catching this exception, and in many instances, this will be all you need.

    3

    Add any unique features for your exception. You may want your exception class to have some unique features above and beyond the ability to be thrown and caught with a stack trace print out. So, you will add some new information to your exception class.

    public class BadUserInputException extends Exception
    private String inputString;

    public getInputString() return (inputString);

    public BadUserInputException(String input)
    super();
    inputString = input;
    ;

    Now, your exception will have an extra function, getInputString(), which can be called anytime your exception is thrown to get a copy of the bad user input in question to be printed to an error log or examined by the program to determine what to do next.

    4

    Add a throw statement to functions that may cause the exception to occur. An exception is worthless unless it is thrown by some function. A throw statement essentially passes an error up the stack to allow a higher level part of the program to determine what should be done with it. This BadUserException will be thrown by a getUserInput() function, appropriately enough:

    /**
    * Javadoc for getUserInput. You want to mention here
    * that this function throws a BadUserInputException
    * so you know to catch it later.
    * @throws BadUserInputException If bad input occurs.
    * @return the user's input if no exception is thrown.
    */
    public String getUserInput() throws BadUserInputException
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String input = in.readLine();
    if (!validInput(input) throw BadUserInputException(input);
    else return input;

    5

    Add code to catch the exception when functions using it are used. This will allow your program to react to errors in a cleanly controlled manner. The code to do so will look like this simple example:

    public void gameLoop()
    try
    printMenu();
    String choice = getUserInput();
    if (choice.equals("Q")) quit();
    else continue();
    catch (BadUserIputException e)
    System.out.println("ERROR: " + e.getInputString() + " : is not valid input.);

Blog Archive