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 ...
随机推荐
- Android 调用系统通讯录
这个过程有三步:1)许可向你的应用程序的manifest中添加读取通讯录数据的许可 <uses-permission android:name="android.permission ...
- python-摩斯码转换
意义:简单实现摩斯码的破译和生成 代码: #-*- coding: UTF-8 -*- ' __date__ = '2016/2/2' import pprint import re chars = ...
- Linux中的cron计划任务配置方法(详细)
cron来源于希腊单词chronos(意为“时间”),指Linux系统下一个自动执行指定任务的程序(计划任务) 1. crontab命令选项 #crontab -u <-l, -r, -e> ...
- Oracle GoldenGate学习之Goldengate介绍
Oracle GoldenGate学习之Goldengate介绍 (2012-10-02 17:07:27) 标签: 检查点 数据传输 队列 进程 分类: Goldengate Goldengate介 ...
- Oracle EBS-SQL (GL-2):从总帐追溯到库存
SELECT je_header_id,je_line_num,trx_class_name, trx_type_name, trx_number_displayed, trx_date, comme ...
- 7816的报文结构——APDU
命令APDU 包括头和主体(这可以在上面的图中看到).头包括CLA,INS,P1 和P2 域.同T0 协议一样,CLA 和INS 说明了应用的分类和指令.P1 和P2 用来详细说明具体指令,并由每一条 ...
- Ubuntu 13.04 小米2S连接Eclipse真机调试
最近想继续将自己以前的一些Android程序代码进行改进和优化,遂将以前的代码在windows下导入eclipse工程,谁知导入后便eclipse假死,甚至windows资源管理器也动弹不得,诡异的是 ...
- (十一年)unity4.6得知Ugui中国文献-------参考-UGUI Visual Components
大家好,我是太阳广东. 转载请注明出处:http://write.blog.csdn.net/postedit/38922399 更全的内容请看我的游戏蛮牛地址:http://www.unity ...
- WebConfig特殊字符的转义!
Web.Config默认编码格式为UTF-8,对于XML文件,要用到实体转义码来替换.对应关系如下: 字符 转义码 & 符号 & & 单引号 ' ' 双引号 ...
- spm3 基本
spm3 命令 spm init //初始化一个spm模块,会生成基本配置以及测试文件等(下图). //注 初始化以后一般需要 鲜执行一下 spm install 安装默认依赖模块 index.js就 ...