如何在Java中创建自定义异常
时间:2020-02-23 14:34:17 来源:igfitidea点击:
在本教程中,我们将看到如何在Java中创建自定义异常。
在Java中创建自定义异常非常简单。
我们只需要扩展异常类以创建自定义异常。
我们有country的名单,如果我们在国家/地区中有"USA",则需要抛出InvalidCountryException(我们的自定义异常)。
示例:创建InvalidCountryException.java,如下所示
package org.igi.theitroad;
public class InvalidCountryException extends Exception{
InvalidCountryException(String message)
{
super(message);
}
}
创建叫做Country.java的Pojo类
package org.igi.theitroad;
public class Country {
private String name;
Country(String name ){
this.name = name;
}
public String toString() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
让我们创建CountryCheckmain.java。
此类将具有主要方法。
package org.igi.theitroad;
import java.util.ArrayList;
import java.util.List;
public class CountryCheckMain {
public static void main(String args[]) {
List countries = new ArrayList();
Country NetherlandsCountry = new Country("Netherlands");
Country chinaCountry = new Country("China");
Country nepalCountry = new Country("Nepal");
Country bhutanCountry = new Country("Bhutan");
countries.add(NetherlandsCountry);
countries.add(chinaCountry);
countries.add(nepalCountry);
countries.add(bhutanCountry);
boolean safe;
try {
safe = checkListOfCountries(countries);
if (safe)
System.out.println("We don't have USA in list of Countries");
Country USACountry = new Country("USA");
countries.add(USACountry);
checkListOfCountries(countries);
} catch (InvalidCountryException e) {
e.printStackTrace();
}
}
public static boolean checkListOfCountries(List countries) throws InvalidCountryException {
for (int i = 0; i < countries.size(); i++) {
Country country = countries.get(i);
if (country.getName().equals("USA")) {
throw new InvalidCountryException("USA is not allowed");
}
}
return true;
}
}
运行上面的程序时,我们将获取以下输出:
We don't have USA in list of Country org.igi.theitroad.comvalidCountryException: USA is not allowed at org.igi.theitroad.CountryCheckMain.checkListOfCountries(CountryCheckMain.java:37) at org.igi.theitroad.CountryCheckMain.main(CountryCheckMain.java:25)
正如我们所看到的,如果我们在国家名单中有"美国",我们正在抛出InvalidCountryException。

