提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
在进行数据库的添加时我们可能会碰到输入的某个参数与数据库中存在的某参数相同,但是该参数是unique约束,所以添加时我们会报错,这次操作时是为了明白是报什么错误
提示:以下是本篇文章正文内容,下面案例可供参考
一、自定义异常类?
public class DuplicateCodeException extends Exception{
/**
* Constructs a new exception with {@code null} as its detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*/
public DuplicateCodeException() {
}
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public DuplicateCodeException(String message) {
super(message);
}
}
二、使用步骤
1.在工具类的代码位置进行添加异常
代码如下(示例):
protected int update(String sql,List list) throws DuplicateCodeException{
getPps(sql);
param(list);
try {
count= pps.executeUpdate();
} catch (SQLException e) {
// e.printStackTrace();
if (e.getMessage().endsWith("for key 'express.code'")){
//是因为取件码重复
DuplicateCodeException e1 = new DuplicateCodeException(e.getMessage());
throw e1;
}else{
e.printStackTrace();
}
}
return count;
}
if (e.getMessage().endsWith("for key 'express.code'"))
该字符串:"for key ‘express.code’“是getMessage()的部分结尾,整体代码不同会有不同的结果字符串,可以通过getMessage()方法进行查看,一般类似于"for key ‘code’”。
2.在dao的实现层添加
代码如下(示例):
public boolean insert(Express express) throws DuplicateCodeException{
int k = 0;
try {
String sql = "INSERT INTO EXPRESS (NUMBER,USERNAME,USERPHONE,COMPANY,CODE,INTIME,STATUS,SYSPHONE) VALUES(?,?,?,?,?,NOW(),0,?)";
List params = new ArrayList();
params.add(express.getNumber());
params.add(express.getUserName());
params.add(express.getUserPhone());
params.add(express.getCompany());
params.add(express.getCode());
params.add(express.getSysphone());
k = update(sql, params);
} catch (Exception e) {
if (e.getMessage().endsWith("for key 'express.code'")){
//是因为取件码重复
DuplicateCodeException e1 = new DuplicateCodeException(e.getMessage());
throw e1;
}else{
e.printStackTrace();
}
} finally {
closeAll();
}
if (k > 0) {
return true;
}
return false;
}
因为我项目的架构问题,所有在MySQL的代码层和insert()方法实现层都需要进行异常处理(如果有不同的结果可以一起交流)
总结
提示:这里对文章进行总结:
以上就是今天碰到的自定义异常类,来进行项目所需的功能的书写,处理异常让程序更加顺畅,程序员阅读更加便利。