J2EE项目中异常处理
- public String getPassword(String userId)throws DataAccessException{
- String sql = “select password from userinfo where userid=’”+userId +”’”;
- String password = null;
- Connection con = null;
- Statement s = null;
- ResultSet rs = null;
- try{
- con = getConnection();//获得数据连接
- s = con.createStatement();
- rs = s.executeQuery(sql);
- while(rs.next()){
- password = rs.getString(1);
- }
- rs.close();
- s.close();
- }
- Catch(SqlException ex){
- throw new DataAccessException(ex);
- }
- finally{
- try{
- if(con != null){
- con.close();
- }
- }
- Catch(SQLException sqlEx){
- throw new DataAccessException(“关闭连接失败!”,sqlEx);
- }
- }
- return password;
- }
- public String getPassword(String userId){
- try{
- ……
- Statement s = con.createStatement();
- ……
- Catch(SQLException sqlEx){
- ……
- }
- ……
- }
或者
- public String getPassword(String userId)throws SQLException{
- Statement s = con.createStatement();
- }
- String str = “123”;
- int value = Integer.parseInt(str);
- public static int parseInt(String s) throws NumberFormatException
- try{
- ……
- Statement s = con.createStatement();
- ……
- Catch(SQLException sqlEx){
- sqlEx.PrintStackTrace();
- }
- 或者
- try{
- ……
- Statement s = con.createStatement();
- ……
- Catch(SQLException sqlEx){
- //什么也不干
- }
- public void methodA()throws ExceptionA{
- …..
- throw new ExceptionA();
- }
- public void methodB()throws ExceptionB{
- try{
- methodA();
- ……
- }catch(ExceptionA ex){
- throw new ExceptionB(ex);
- }
- }
- Public void methodC()throws ExceptinC{
- try{
- methodB();
- …
- }
- catch(ExceptionB ex){
- throw new ExceptionC(ex);
- }
- }
我们看到异常就这样一层层无休止的被封装和重新抛出。
如
- IllegalArgumentException, UnsupportedOperationException
- public void methodA()throws ExceptionA{
- …..
- throw new ExceptionA();
- }
- public void methodB()throws ExceptionB{
- try{
- methodA();
- ……
- }catch(ExceptionA ex){
- throw new ExceptionB(ex);
- }
- }
- public Class ExceptionB extends Exception{
- private Throwable cause;
- public ExceptionB(String msg, Throwable ex){
- super(msg);
- this.cause = ex;
- }
- public ExceptionB(String msg){
- super(msg);
- }
- public ExceptionB(Throwable ex){
- this.cause = ex;
- }
- }
当然,我们在调用printStackTrace方法时,需要把所有的“起因异常”的信息也同时打印出来。所以我们需要覆写printStackTrace方法来显示全部的异常栈跟踪。包括嵌套异常的栈跟踪。
- public void printStackTrace(PrintStrean ps){
- if(cause == null){
- super.printStackTrace(ps);
- }else{
- ps.println(this);
- cause.printStackTrace(ps);
- }
- }
- public NestedException extends Exception{
- private Throwable cause;
- public NestedException (String msg){
- super(msg);
- }
- public NestedException(String msg, Throwable ex){
- super(msg);
- This.cause = ex;
- }
- public Throwable getCause(){
- return (this.cause == null ? this :this.cause);
- }
- public getMessage(){
- String message = super.getMessage();
- Throwable cause = getCause();
- if(cause != null){
- message = message + “;nested Exception is ” + cause;
- }
- return message;
- }
- public void printStackTrace(PrintStream ps){
- if(getCause == null){
- super.printStackTrace(ps);
- }else{
- ps.println(this);
- getCause().printStackTrace(ps);
- }
- }
- public void printStackTrace(PrintWrite pw){
- if(getCause() == null){
- super.printStackTrace(pw);
- }
- else{
- pw.println(this);
- getCause().printStackTrace(pw);
- }
- }
- public void printStackTrace(){
- printStackTrace(System.error);
- }
- }
同样要设计一个unChecked异常类也与上面一样。只是需要继承RuntimeException。
- public String getPassword(String userId)throws NoSuchUserException{
- UserInfo user = userDao.queryUserById(userId);
- If(user == null){
- Logger.info(“找不到该用户信息,userId=”+userId);
- throw new NoSuchUserException(“找不到该用户信息,userId=”+userId);
- }
- else{
- return user.getPassword();
- }
- }
- public void sendUserPassword(String userId)throws Exception {
- UserInfo user = null;
- try{
- user = getPassword(userId);
- //……..
- sendMail();
- //
- }catch(NoSuchUserException ex)(
- logger.error(“找不到该用户信息:”+userId+ex);
- throw new Exception(ex);
- }
- public Date getDate(String str){
- Date applyDate = null;
- SimpleDateFormat format = new SimpleDateFormat(“MM/dd/yyyy”);
- try{
- applyDate = format.parse(applyDateStr);
- }
- catch(ParseException ex){
- //乎略,当格式错误时,返回null
- }
- return applyDate;
- }
- try{
- ……
- String sql=”select * from userinfo”;
- Statement s = con.createStatement();
- ……
- Catch(SQLException sqlEx){
- Logger.error(“sql执行错误”+sql+sqlEx);
- }
- public class BusinessException extends Exception {
- private void logTrace() {
- StringBuffer buffer=new StringBuffer();
- buffer.append("Business Error in Class: ");
- buffer.append(getClassName());
- buffer.append(",method: ");
- buffer.append(getMethodName());
- buffer.append(",messsage: ");
- buffer.append(this.getMessage());
- logger.error(buffer.toString());
- }
- public BusinessException(String s) {
- super(s);
- race();
- }
这似乎看起来是十分美妙的,其实必然导致了异常被重复记录。同时违反了“类的职责分配原则”,是一种不好的设计。记录异常不属于异常类的行为,记录异常应该由专门的日志系统去做。并且异常的记录信息是不断变化的。我们在记录异常同应该给更丰富些的信息。以利于我们能够根据异常信息找到问题的根源,以解决问题。
- //
- public class UserSoaImpl implements UserSoa{
- public UserInfo getUserInfo(String userId)throws RemoteException{
- //……
- 远程方法调用.
- //……
- }
- }
- public interface UserManager{
- public UserInfo getUserInfo(Stirng userId)throws RemoteException;
- }
- public DataAccessException extends RuntimeException{
- ……
- }
- public interface UserDao{
- public String getPassword(String userId)throws DataAccessException;
- }
- public class UserDaoImpl implements UserDAO{
- public String getPassword(String userId)throws DataAccessException{
- String sql = “select password from userInfo where userId= ‘”+userId+”’”;
- try{
- …
- //JDBC调用
- s.executeQuery(sql);
- …
- }catch(SQLException ex){
- throw new DataAccessException(“数据库查询失败”+sql,ex);
- }
- }
- }
- public class BusinessException extends Exception{
- …..
- }
- public interface UserManager{
- public Userinfo copyUserInfo(Userinfo user)throws BusinessException{
- Userinfo newUser = null;
- try{
- newUser = (Userinfo)user.clone();
- }catch(CloneNotSupportedException ex){
- throw new BusinessException(“不支持clone方法:”+Userinfo.class.getName(),ex);
- }
- }
- }
- ModeAndView handleRequest(HttpServletRequest request,HttpServletResponse response)throws Exception{
- String ageStr = request.getParameter(“age”);
- int age = Integer.parse(ageStr);
- …………
- String birthDayStr = request.getParameter(“birthDay”);
- SimpleDateFormat format = new SimpleDateFormat(“MM/dd/yyyy”);
- Date birthDay = format.parse(birthDayStr);
- }
- ModeAndView handleRequest(HttpServletRequest request,HttpServletResponse response)throws Exception{
- String ageStr = request.getParameter(“age”);
- String birthDayStr = request.getParameter(“birthDay”);
- int age = 0;
- Date birthDay = null;
- try{
- age=Integer.parse(ageStr);
- }catch(NumberFormatException ex){
- error.reject(“age”,”不是合法的整数值”);
- }
- …………
- try{
- SimpleDateFormat format = new SimpleDateFormat(“MM/dd/yyyy”);
- birthDay = format.parse(birthDayStr);
- }catch(ParseException ex){
- error.reject(“birthDay”,”不是合法的日期,请录入’MM/dd/yyy’格式的日期”);
- }
- }
转载于:https://www.cnblogs.com/liaoliao/p/5009152.html
J2EE项目中异常处理相关推荐
- 编写高质量代码改善java程序的151个建议——[110-117]异常及Web项目中异常处理
编写高质量代码改善java程序的151个建议--[110-117]异常及Web项目中异常处理 原创地址:http://www.cnblogs.com/Alandre/(泥沙砖瓦浆木匠),需要转载的,保 ...
- J2EE项目中异常的设计与处理
异常设计 0.J2EE中的异常设计3层结构 Dao,Service,Controller异常处理原则:应该在Controller控制转发之前尽量处理,同时记录log日志,然后在页面以友好的错误提示告诉 ...
- java代码异常处理会影响性能_编写高质量代码改善java程序的151个建议——[110-117]异常及Web项目中异常处理...
原创地址:http://www.cnblogs.com/Alandre/(泥沙砖瓦浆木匠),需要转载的,保留下! 文章宗旨:Talk is cheap show me the code. 大成若缺,其 ...
- 关于J2EE项目中三层架构如何在开发中得到正确的实施
我现在参与了一个广电项目的开发,项目采用了目前比较流行的框架进行系统的架构Struts2+sping+hibernate,项目的包结构主要分成Action.Service.dao这三层,Action层 ...
- 在J2EE项目中集成快钱支付接口
转载地址 [url] http://my.oschina.net/bairrfhoinn/blog/78184[/url] 首先是发送快钱支付请求的页面send.jsp,内容如下: 001 <% ...
- J2EE项目异常处理
转自http://www.iteye.com/topic/72170 为什么要在J2EE项目中谈异常处理呢?可能许多java初学者都想说:"异常处理不就是try ...
- Java EE项目中异常设计及处理总结
异常设计 0.J2EE中的异常设计3层结构 Dao,Service,Controller异常处理原则:应该在Controller控制转发之前尽量处理,同时记录log日志,然后在页面以友好的错误提示告诉 ...
- 在vue项目中:统一封装 Axios 接口与异常处理
在vue项目中:统一封装 Axios 接口与异常处理 参考文章: (1)在vue项目中:统一封装 Axios 接口与异常处理 (2)https://www.cnblogs.com/itgezhu/p/ ...
- J2EE学习中一些值得研究的开源项目(转载天极网)
J2EE学习中一些值得研究的开源项目 这篇文章写在我研究J2SE.J2EE近三年后.前3年我研究了J2SE的Swing.Applet.Net.RMI.Collections.IO.JNI--研究了J2 ...
- J2EE学习中一些值得研究的开源项目
这篇文章写在我研究J2SE.J2EE近三年后.前3年我研究了J2SE的Swing.Applet.Net.RMI.Collections. IO.JNI--研究了J2EE的JDBC.Sevlet.JSP ...
最新文章
- Ubuntu文件的复制、移动和删除命令
- Odoo(OpenERP)配置文件openerp-server.conf详解
- 长篇问答任务(LFQA)的发展面临哪些阻碍?
- HTML5 Canvans 常用API整理
- python -lambda表达式的用法
- 新年迈出Java后台服务器与数据库交互第一步2022最新通用Java8jdbc8连接mysql8数据库进行增删改查等基本操作详解(IDEA),jar包导入,图片等文件流,批量操作
- [react] 在使用react过程中你都踩过哪些坑?你是怎么填坑的?
- 数据中台建设与应用_Gartner对于建设数据中台的建议
- layui option 动态添加_layui select动态添加option的实例
- 如何使用Bioconductor进行单细胞分析?
- Angular Material design设计
- Linux基础命令---mke2fs
- ap6212linux驱动下载,AP6212各个版本固件
- html表格序号自动增加
- Java:Stream三部曲(三):Stream流处理器
- mac笔记本怎么外接显示屏_Mac电脑外接显示器全攻略
- SQL实战39.针对上面的salaries表emp_no字段创建索引idx_emp_no,查询emp_no为10005,
- MYSQL中,CAST函数的使用规则
- 使用DirectDraw直接显示YUV视频数据
- 回归预测 | MATLAB实现PLS(偏最小二乘法)和PCR(主成分回归)多输入单输出