import java.sql.Connection;import java.io.IOException;
import java.sql.SQLException;//java异常处理
//异常
public class test82 {//定义方法声明定义异常,在满足条件时抛出异常对象,程序转向异常处理public double count(double n, double m, Connection conn)throws ArithmeticException,SQLException {if (m == 0) {//如果除数等于0.则抛出异常实例throw new ArithmeticException("对不起。除数不能等于0");}if(conn==null||conn.isClosed()){throw new SQLException( "数据库连接失败" );}return n/m;}
}
测试类
import java.sql.Connection;
import java.sql.SQLException;public class test80 {//定义了编译异常的方法调用,必须进行显示处理public static void main(String[] args){test82 com=new test82();Connection conn = null;try {double t = com.count( 78, 2, conn );//子类异常必须放在前面}catch (SQLException e){String msg = e.getMessage();System.err.println( msg );e.printStackTrace();//打印异常轨迹}catch (Exception e){String msg = e.getMessage();System.err.println( msg );e.printStackTrace();//打印异常轨迹}finally {//强制执行的代码,通常执行释放被占用的资源System.out.println( "开始资源释放" );try {conn.close();}catch (SQLException e){e.printStackTrace();}System.out.println( "资源释放完毕" );}}
}
运行结果