异常处理--【J2SE】

异常概念

  程序运行期出现的异常事件。良好的程序应该在异常发生的时候提供处理这些异常的方法,使得程序不会因为异常的发生而阻断或产生不可预见的结果。

异常处理原理

  异常处理--【J2SE】_第1张图片
  

异常分类

异常处理--【J2SE】_第2张图片
Throwable是所有错误或异常的超类。
Exception指出了合理的应用程序想要捕获的条件。
RuntimeException是可能在Java虚拟机正常运行期间抛出的异常的超类。
Error用于指示合理的应用程序不应该试图捕获的严重问题。

使用异常的Demo:



 import java.io.*; public class TestEx{ public static void main(String args[]){ FileInputStream in =null; try{ in =new FileInputStream("myfile.txt");//必须对它进行捕捉或声明抛出 int b; b=in.read(); while(b!=-1){ // System.out.print((char )b); System.out.print((char)b); b=in.read(); } }catch(FileNotFoundException e){//可以在try后面加多个Catch来捕获异常,但是遵循先小后大 e.printStackTrace(); }catch(IOException e){ System.out.println(e.getMessage()); }finally{ try{ in.close(); }catch(IOException e){ e.printStackTrace(); } } } void m(int i ) throws ArithmeticException{ if (i==0){ throw new ArithmeticException("被除数为0"); } } } 

捕获异常前程序运行结果:
异常处理--【J2SE】_第3张图片

异常捕获处理

关键字

try: 包含可能产生例外的代码 ,后面跟一个或多个catch代码段。
catch:声明处理的一种特定类型的异常并提供处理的方法。
finally:异常发生,程序会终止当前的流程,根据获取异常去执行相应的catch代码,但是无论异常是否产生,程序始终会执行相应的finally代码段,一般释放资源的代码经常写在finally里面。比如:打开一个文件,无论出错不出错,都要把文件关闭,在finally面就写把文件关闭的代码。
throw:抛出一个具体的异常类型。常在方法内通过throw声明一个具体的异常信息。需要用户自己捕获,然后对其进行相关包装,最后在将包装后的异常信息抛出。
throws:用来声明一个方法可能抛出的所有异常信息。通过在一个方法的声明处定义通过throws声明方法可能抛出的异常信息。
实例:

public Test()throws RepletException{
    try{
      System.out.println("Test this Project!")
       }
       catch(Exception e){
       throw new Exception(e.toString());
       }
 }

总结

一个优秀的程序员,要有良好的编程习惯。异常处理是必不可缺的代码能力之一。异常处理让接受和处理错误代码进行解耦和。理清了编程者的思绪,增强了代码的可读性,方便了维护者的阅读和理解。

2016年1月26日 补充DRP中学的一个异常的实例:

package com.bjpowernode.drp.basedata.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.bjpowernode.drp.basedata.domain.Item;
import com.bjpowernode.drp.util.ApplicationException;
import com.bjpowernode.drp.util.DbUtil;
import com.bjpowernode.drp.util.PageModel;

/** * @ClassName:ItemDao4OracleImpl * @Description:物料Oracle的具体实现 * @author wm * @date 2016年1月25日下午4:12:30 */
public class ItemDao4OracleImpl implements ItemDao {


    public void addItem(Connection conn, Item item) {

        String sql="insert into drp1.t_items (item_no,item_category_id,item_unit_id,item_name,spec,pattern, rowid)";
                sql+= "values(?,?,?,?,?,?,?)";
        PreparedStatement pstmt=null;
        try {
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1, item.getItemNO());
            pstmt.setString(2, item.getItemName());
            pstmt.setString(3, item.getSpec());
            pstmt.setString(4, item.getPattern());
            pstmt.setString(5, item.getItemCategory().getId());
            pstmt.setString(6, item.getItemUnit().getId());
            pstmt.executeUpdate(); 
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ApplicationException("添加物料失败!");

        }finally{
            DbUtil.close(pstmt);
        }
    }


}

运行时异常处理类:

/** * */
package com.bjpowernode.drp.util;

/** * @ClassName:ApplicationException * @Description:运行期异常 * @author wm * @date 2016年1月26日下午2:14:08 */
public class ApplicationException extends RuntimeException {

    /** * */
    public ApplicationException() {
        // TODO Auto-generated constructor stub
    }

    /** * @param message */
    public ApplicationException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    /** * @param cause */
    public ApplicationException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    /** * @param message * @param cause */
    public ApplicationException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    /** * @param message * @param cause * @param enableSuppression * @param writableStackTrace */
    public ApplicationException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

}

补充:2016年1月28日

异常的处理方式

1.根据每种业务语义创建不同的异常,如果UserNotFoundException
2.每层抛出相应的异常,如DaoException ,ServiceException
3.每个模块抛出一种异常,如SysMgrException
4.只抛出一种异常,如AppException
5.错误码可以做到异常粒度划分,采用错误码可以减少异常类的建立。

异常处理--【J2SE】_第4张图片

你可能感兴趣的:(java,exception,异常处理,J2SE)