有些时候,我们需要通过自己定义的异常信息输出
首先,定义一个异常类
public class U_Customed_Exception extends Exception{
public U_Customed_Exception(String msg){
super(msg);
}
}
然后,在其他类中引用这个异常类
import com.qa.ballon.api.util.U_Customed_Exception;
public class U_File_Properties {
private static Logger logger = Logger.getLogger(U_File_Properties.class);
public static HashMap<String,String> dbproperties = new HashMap<String, String>();
//用于获取数据库配置文件的各项信息
//要在方法中显示声明抛出的自定义异常类
public void M_get_db_propertise(String propath,String dbtype) throws U_Customed_Exception{
Properties dbprop = new Properties();
try{
InputStream ins = getClass().getResourceAsStream(propath);
dbprop.load(ins);
logger.info("the database.propertise has got successfully!!");
}catch(Exception e){
logger.error("the database.propertise has some problems!!");
e.printStackTrace();
}
if(dbtype.equals("mysql"))
{
try {
dbproperties.put("mysql.ip", dbprop.getProperty("mysql.ip"));
logger.info("the database info has got successfully!!");
} catch (Exception e) {
// TODO: handle exception
logger.error("Failed to collect database info,please check the keyword and values!!");
e.printStackTrace();
}
}else {
logger.error("no such type of database then~~~ dbtype you gived is "+dbtype);
<span style="white-space:pre"> </span>//创建新的异常实例,抛出异常信息
throw new U_Customed_Exception("no such type of database!! the type of database you gived is "+dbtype);
}
}
当我们执行的内容,输入的dbtype不是我们所期望的'mysql'时,则直接抛出异常,输出的结果如下:
Exception in thread "main" com.qa.ballon.api.util.U_Customed_Exception: no such type of database!! the type of database you gived is sql
at com.qa.ballon.api.util.U_File_Properties.M_get_db_propertise(U_File_Properties.java:52)
at com.qa.ballon.api.util.U_File_Properties.main(U_File_Properties.java:60)