Java EE项目中的异常处理 (实在写的太好了,导致我非法转载!!!)
为什么要在J2EE项目中谈异常处理呢?可能许多java初学者都想说:“异常处理不就是try….catch…finally吗?这谁都会啊!”。笔者在初学java时也是这样认为的。如何在一个多层的j2ee项目中定义相应的异常类?在项目中的每一层如何进行异常处理?异常何时被抛出?异常何时被记录?异常该怎么记录?何时需要把checked Exception转化成unchecked Exception ,何时需要把unChecked Exception转化成checked Exception?异常是否应该呈现到前端页面?如何设计一个异常框架?本文将就这些问题进行探讨。1. JAVA异常处理在面向过程式的编程语言中,我们可以通过返回值来确定方法是否正常执行。比如在一个c语言编写的程序中,如果方法正确的执行则返回1.错误则返回0。在vb或delphi开发的应用程序中,出现错误时,我们就弹出一个消息框给用户。通过方法的返回值我们并不能获得错误的详细信息。可能因为方法由不同的程序员编写,当同一类错误在不同的方法出现时,返回的结果和错误信息并不一致。所以java语言采取了一个统一的异常处理机制。什么是异常?运行时发生的可被捕获和处理的错误。在java语言中,Exception是所有异常的父类。任何异常都扩展于Exception类。Exception就相当于一个错误类型。如果要定义一个新的错误类型就扩展一个新的Exception子类。采用异常的好处还在于可以精确的定位到导致程序出错的源代码位置,并获得详细的错误信息。Java异常处理通过五个关键字来实现,try,catch,throw ,throws, finally。具体的异常处理结构由try….catch….finally块来实现。try块存放可能出现异常的java语句,catch用来捕获发生的异常,并对异常进行处理。Finally块用来清除程序中未释放的资源。不管理try块的代码如何返回,finally块都总是被执行。一个典型的异常处理代码java 代码
- 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 staticint 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);}
- }
如java 代码不管是新的异常是chekced异常还是unChecked异常。我们都必须考虑异常的嵌套问题。java 代码
- 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;
- } }
- 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);
- } }
- 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 UserSoaImplimplements UserSoa{
- public UserInfo getUserInfo(String userId)throws RemoteException{//……
- 远程方法调用. //……
- } }
- public interface UserManager{public UserInfo getUserInfo(Stirng userId)throws RemoteException;
- }
- public DataAccessExceptionextends RuntimeException{……
- } public interface UserDao{
- public String getPassword(String userId)throws DataAccessException;}
- public class UserDaoImplimplements 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 BusinessExceptionextends 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’格式的日期”); }
- }