try-catch-finally语句块通常用于处理程序中可能出现的异常情况,例如:
- 文件操作:在读取或写入文件时,可能会出现IO异常。使用try-catch-finally语句块可以捕获并处理这些异常,确保程序不会崩溃。
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
File file = new File("test.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("关闭文件流");
}
}
}
- 数据库操作:在使用数据库时,可能会出现SQL异常。使用try-catch-finally语句块可以捕获并处理这些异常,确保程序不会崩溃。
import java.sql.*;
public class DatabaseDemo {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
System.out.println(resultSet.getString("username"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
- 网络通信:在进行网络通信时,可能会出现网络异常。使用try-catch-finally语句块可以捕获并处理这些异常,确保程序不会崩溃。
- 其他可能抛出异常的操作:例如,调用方法时可能会抛出异常,使用try-catch-finally语句块可以捕获并处理这些异常,确保程序不会崩溃。