Java异常处理:常见场景与案例
在Java编程中,异常处理是防止程序因意外情况而崩溃的重要机制。以下是一些常见的Java异常处理场景和案例:
文件操作:
- 检查文件是否存在:
File file = new File("path/to/file.txt");
if (!file.exists()) {
throw new IllegalArgumentException("File does not exist.");
}
读写文件,捕获可能的IOException异常:
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("file.txt")));
// 读取内容
String content = br.readLine();
System.out.println(content);
} catch (IOException e) {
e.printStackTrace(); // 或者使用处理方式,如记录日志等
if (br != null) {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
throw new RuntimeException("Error reading file.", e);
}
finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
// 确保文件关闭,即使发生异常
}
}
- 检查文件是否存在:
网络通信:
发送HTTP请求,捕获可能的Exception:
try {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
// 请求成功,读取响应内容
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
String content = br.readLine();
System.out.println(content);
} else {
// 请求失败或状态码不为200
System.out.println("Request failed with response code " + responseCode));
}
} catch (Exception e) {
e.printStackTrace(); // 或者使用处理方式,如记录日志等
System.out.println("An error occurred during request execution.");
}
数据库操作:
连接数据库,捕获可能的SQLException异常:
Connection connection = null;
try {
// 创建连接对象
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc
//localhost:3306/mydatabase",
"username",
"password"
);
// 执行SQL语句
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
// 处理查询结果
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("An error occurred while executing SQL queries.");
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException se) {
se.printStackTrace();
System.out.println("Error closing database connection.");
}
}
}
以上例子展示了Java中处理不同异常情况的常见场景。在实际编程中,需要根据具体需求和异常类型进行相应的异常处理。
还没有评论,来说两句吧...