How do I throw an exception in my Java code?

supahot :

I got a method that prints out the animals' names. I now need an error to be printed out if the id is not one of the given ones. How does it work?

class Methode {
    static final int DEER = 0;
    static final int BIRD = 1;
    static final int COW = 2;
    static final int PIG = 3;

    public static void main(String[] args) {
            printAnimal();
    }

    public static void printAnimal (int id) {
        if (id == DEER) {
            System.out.println("Deer");
        }
        else if (id == BIRD) {
            System.out.println("Bird");
        }
        else if (id == COW) {
                System.out.println("COW");
        }
        else if (id == PIG) {
            System.out.println("Pig");
        }
    }
}
Sebastian I. :

If by error you mean an Exception (otherwise I don't know why you didn't simply printed an "error" message like you did in your else if branches), then you need to create a custom class which extends Exception and throw it in a new else branch. Here is an example:

Exception:

public class NoSuchAnimalException extends Exception {
 public NoSuchAnimalException(String message) {
     super(message);
 }
}

Test:

public static void printAnimal(int id) throws NoSuchAnimalException {
    if (id == DEER) {
        System.out.println("Deer");
    } else if (id == BIRD) {
        System.out.println("Bird");
    } else if (id == COW) {
        System.out.println("COW");
    } else if (id == PIG) {
        System.out.println("Pig");
    } else {
        throw new NoSuchAnimalException("No such animal");
    }
}

public static void main(String[] args) {
    try {
        printAnimal(6);
    } catch (NoSuchAnimalException e) {
        System.out.println(e.getMessage());
    }
}

The exception will be thrown in the last else (the id provided in method call doesn't meet the previous requirements) and will be handled in the public static void main() method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11664&siteId=1