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’格式的日期”);
- }
- }
J2EE项目中异常处理的更多相关文章
- 编写高质量代码改善java程序的151个建议——[110-117]异常及Web项目中异常处理
原创地址:http://www.cnblogs.com/Alandre/(泥沙砖瓦浆木匠),需要转载的,保留下! 文章宗旨:Talk is cheap show me the code. 大成若缺,其 ...
- J2EE项目中后台定时运行的程序
转自:http://www.2cto.com/kf/201311/260676.html 在开发J2EE项目中,有时候需要在后台定时执行一些代码. 比如定时对web数据建立倒排索引.定时发送邮件.定时 ...
- java项目中异常处理情况
一,基本概念 异常是程序在运行时出现的不正常情况.是Java按照面向对象的思想将问题进行对象封装.这样就方便于操作问题以及处理问题. 异常处理的目的是提高程序的健壮性.你可以在catch和fin ...
- J2EE项目中,servlet跳转到相应的JSP页面后,JSP页面丢失了样式效果
原因: js和css的引用路径是相对路径.跳转后路径改变. 解决方法: 先在head标签中加入一下代码 <% String path = request.getContextPath(); St ...
- 关于JAVA项目中的常用的异常处理情况总结
1. JAVA异常处理 在面向过程式的编程语言中,我们可以通过返回值来确定方法是否正常执行.比如在一个c语言编写的程序中,如果方法正确的执行则返回1.错误则返回0.在vb或delphi开发的应用程序中 ...
- J2EE项目异常处理(转)
为什么要在J2EE项目中谈异常处理呢?可能许多java初学者都想说:“异常处理不就是try….catch…finally吗?这谁都会啊!”.笔者在初学java时也是这样认为的.如何在一个多层的j2e ...
- JAVA项目中常用的异常处理情况总结
JAVA项目中常用的异常知识点总结 1. java.lang.nullpointerexception这个异常大家肯定都经常遇到,异常的解释是"程序遇上了空指针",简单地说就是调用 ...
- WEB 项目中的全局异常处理
在web 项目中,遇到异常一般有两种处理方式:try.....catch....:throw 通常情况下我们用try.....catch.... 对异常进行捕捉处理,可是在实际项目中随时的进行异常捕捉 ...
- 【J2EE】在项目中理解J2EE规范
J2EE平台由一整套服务(Service),应用程序接口(API)和协议构成,它对开发企业级应用提供了功能支持.13个核心技术各自是JDBC, JNDI, EJB, RMI, JSP ...
随机推荐
- js监听input等表单输入框的变化事件oninput
js监听input等表单输入框的变化事件oninput,手机页面开发中使用到文本框textarea输入字符监听文本框变化计算还可以输入多少字符,如果使用onkeyup的话是无法监听到输入法输入的文本变 ...
- [原创]反汇编之一:和Taskmgr过不去篇(无厘头版)
原文链接:和Taskmgr过不去篇(无厘头版) Hook入门级文章,主要想培养一下偶写文章的感觉,老鸟无视…我想看看技术文章能不能无厘头的写,如果效果不错的话,准备更上一层-----用我的原创漫画表达 ...
- 用C语言制作小型商品信息管理系统过程中的问题
大神请默默飘过... 以下是第一次制作时的源码: // 商品信息管理.cpp : 定义控制台应用程序的入口点. // // 小型商品信息管理系统.cpp : 定义控制台应用程序的入口点. // #in ...
- 每天学点Linux:一
软链接和硬链接: 软链接,又称符号链接,它的原理是通过一个文本文件记录真实文件在系统中的位置,然后在文件操作的时候通过该地址查找原文件然后对其操作.类似于Windows里面的快捷方式.软链接可以链接不 ...
- lodash中_.set的用法
_.set(object, path, value) # Ⓢ Ⓣ Ⓝ 设置对象的路径上的属性值.如果路径不存在,则创建它. 参数 1.object (Object): 待扩大的对象. 2.path ( ...
- java写文件时,输出不完整的原因以及解决方法
在java的IO体系中,写文件通常会用到下面语句 BufferedWriter bo=new BufferedWriter(new FileWriter("sql语句.txt")) ...
- 算法精解(C语言描述) 第5章 读书笔记
第5章 5.1 单链表 /* -------------------------------- list.h -------------------------------- */ #ifndef L ...
- prototype演变
setp1 var Person = function () {}; //构造器 var p = new Person(); setp1 演变: var Person = function () {} ...
- java数据库连接
注意点: 1.所有和数据库相关的(jdbc)包都是java.sql.*: 2.将项目所需的jar包统一复制到web-inf/lib文件夹中. 一:sqlsever数据库 package dbcon; ...
- Kettle 学习笔记
一直用SSIS做ETL,越来越感觉这玩意不是亲生的.因此萌生换ETL工具的想法,不过Kettle社区版没什么调度系统,貌似错误处理也不是很方便,且先了解吧. 本文简略的记录了整个软件的使用流程. 开始 ...