[英]How do I throw an exception in my Java code?
我有一種方法可以打印出動物的名字。 如果 id 不是給定的 id 之一,我現在需要打印一個錯誤。 它是如何工作的?
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");
}
}
}
如果錯誤是指Exception
(否則我不知道你為什么不像在else if
分支中那樣簡單地打印“錯誤”消息),那么你需要創建一個擴展Exception
並拋出它的自定義類在一個新的else
分支中。 下面是一個例子:
例外:
public class NoSuchAnimalException extends Exception {
public NoSuchAnimalException(String message) {
super(message);
}
}
測試:
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());
}
}
異常會在最后一個else
拋出(方法調用中提供的id不符合前面的要求),會在public static void main()
方法中處理。
首先,您在不帶參數的情況下調用printAnimal()
方法。 那不好。
其次,Java 中有兩種異常,checked 和 unchecked。 你需要考慮你正在使用哪種類型。
檢查意味着您的函數必須通過以下方式聲明:
methodName() throws SomeException{ ...}
因此,調用者必須捕獲異常。
未經檢查意味着您可以在不這樣做的情況下拋出異常,但其他程序員不會意識到(相反,不會被迫處理)拋出的任何異常。
應該像類一樣創建異常,繼承適當的異常基類型。
檢查異常
class someException extends exception{...}
未經檢查的異常
class someException extends RuntimeException{...}
對於非自定義異常,它們會像這樣拋出:
被檢查的異常
throw new Exception ('message');
未經檢查的異常
throw new RuntimeException ('message');
請閱讀有關異常的Java 文檔。 異常是 OOP 的重要組成部分
(這是在手機上寫的,所以可能有一些錯別字等)
應該為此任務使用枚舉和開關:
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.