简体   繁体   中英

How do I throw an exception in my Java code?

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");
        }
    }
}

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.

Firstly you call your printAnimal() method without a parameter. That's no good.

Secondly, there are two kinda of exceptions in Java, checked and unchecked. You need to consider which kind you're working with.

Checked means your function must be declared by:

methodName() throws SomeException{ ...}

And accordingly a caller MUST catch exceptions.

Unchecked means you can throw the exception without doing this, but other programmers aren't made aware of (and conversely, not forced to handle) any exceptions thrown.

Exceptions should be created, like classes, inheriting the base type of exception appropriate.

Checked exception

class someException extends exception{...}

Unchecked exception

class someException extends RuntimeException{...}

For non custom exceptions they are thrown like so:

The checked exception

throw new Exception ('message');

The unchecked exception

throw new RuntimeException ('message');

Please read the Java doc on exceptions . Exceptions are an important part of OOP

(This was written on a phone, so there might be a few typos etc.)

Should use enums and switch for this task:

public class Methode {

    public enum Animal {
        DEER (0),
        BIRD (1),
        COW (2),
        PIG (3);

        private final int value;
        private static Map valueMap = new HashMap<>();

        Animal(int value)
        {
            this.value = value;
        }

        static {
            for (Animal enumVal : Animal.values()) {
                valueMap.put(enumVal.value, enumVal);
            }
        }

        public static Animal valueOf(int animalId) {
            return (Animal) valueMap.get(animalId);
        }

        public int getValue()
        {
            return value;
        }
    }

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

    public static void printAnimal (int id) throws Exception {
        Animal animal = Animal.valueOf(id);

        if(animal == null) {
            throw new Exception("Animal not found"); //better use own exception
        } else {
            switch (animal) {
                case DEER:
                    System.out.println("Deer");
                    break;
                case BIRD:
                    System.out.println("Bird");
                    break;
                case COW:
                    System.out.println("COW");
                    break;
                case PIG:
                    System.out.println("Pig");
                    break;
                default:
                    System.out.println(animal.name());
            }
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM