简体   繁体   English

如何在我的 Java 代码中抛出异常?

[英]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.如果 id 不是给定的 id 之一,我现在需要打印一个错误。 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.如果错误是指Exception (否则我不知道你为什么不像在else if分支中那样简单地打印“错误”消息),那么你需要创建一个扩展Exception并抛出它的自定义类在一个新的else分支中。 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.异常会在最后一个else抛出(方法调用中提供的id不符合前面的要求),会在public static void main()方法中处理。

Firstly you call your printAnimal() method without a parameter.首先,您在不带参数的情况下调用printAnimal()方法。 That's no good.那不好。

Secondly, there are two kinda of exceptions in Java, checked and unchecked.其次,Java 中有两种异常,checked 和 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 .请阅读有关异常Java 文档 Exceptions are an important part of OOP异常是 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());
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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