java 错误: 未报告的异常错误Exception; 必须对其进行捕获或声明以便抛出

时间:2022-07-06 16:04:31

java 错误: 未报告的异常错误Exception; 必须对其进行捕获或声明以便抛出

 import java.io.FileInputStream;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement; public class ExecuteDML{
private String driver;
private String url;
private String user;
private String pass; public void initParam(String paramFile) throws Exception{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
} public int insertData(String sql) throws Exception{
//加载驱动
Class.forName(driver);
try(
//获取数据库连接
Connection conn = DriverManager.getConnection(url, user, pass);
//使用Connection来创建一个Statement对象
Statement stmt = conn.createStatement()){
//执行SQL语句,返回受影响的记录条数
return stmt.executeUpdate(sql);
}
} public static void main(String[] args) {
ExecuteDML ed = new ExecuteDML();
ed.initParam("mysql.ini");
int result = ed.insertData("insert into jdbc_test(jdbc_name,jdbc_desc)"
+ "select s.student_name , t.teacher_name "
+ "from student_table s , teacher_table t "
+ "where s.java_teacher = t.teacher_id;");
System.out.println("------系统中一共有" + result + "条记录受影响------");
}
}

出错是因为,对initParam()方法和insertData()方法抛出的异常没有进行处理,解决办法:

  1.main()方法中在try...catch块中调用initParam()和insertData()方法

  2.main()方法throws抛出异常。

 import java.io.FileInputStream;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement; public class ExecuteDML{
private String driver;
private String url;
private String user;
private String pass; public void initParam(String paramFile) throws Exception{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
} public int insertData(String sql) throws Exception{
//加载驱动
Class.forName(driver);
try(
//获取数据库连接
Connection conn = DriverManager.getConnection(url, user, pass);
//使用Connection来创建一个Statement对象
Statement stmt = conn.createStatement()){
//执行SQL语句,返回受影响的记录条数
return stmt.executeUpdate(sql);
}
} public static void main(String[] args) throws Exception{
ExecuteDML ed = new ExecuteDML();
ed.initParam("mysql.ini");
int result = ed.insertData("insert into jdbc_test(jdbc_name,jdbc_desc)"
+ "select s.student_name , t.teacher_name "
+ "from student_table s , teacher_table t "
+ "where s.java_teacher = t.teacher_id;");
System.out.println("------系统中一共有" + result + "条记录受影响------");
}
}