public class A {
public static void main(String[] args) {
//java定义一个对象引用并初始化为null,尝试用此引用调用方法。
//把这个电泳放在try-catch中以捕获异常,最后finally子句中输出"异常句子"。
String str = null;
String err = null;
try{
str.equals("abc");//此处必定发生空指针异常
}catch(NullPointerException nullExp){
err = "异常句子";//捕获异常
}finally{
System.out.println(err);//最终输出出错信息
}
}
}
举个例子吧
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?user=root&password=root");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
while (rs.next()) {
System.out.print(rs.getString("deptno") + " ");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();//将异常信息打印出来
} catch (SQLException e) {
e.printStackTrace();//将异常信息打印出来
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();//将异常信息打印出来
}
}