异常捕获与重试:Java中try-catch-finally的应用案例
在Java中,try-catch-finally
语句块用于处理可能出现的异常。下面是一些实际应用案例:
- 文件操作:
```java
import java.io.File;
import java.io.IOException;
public class FileHandling {
public static void main(String[] args) {
try {
// 读取文件
String content = readFile(new File(“example.txt”)));
System.out.println(content);
} catch (IOException e) {
System.err.println(“Error occurred while reading file: “ + e.getMessage());
e.printStackTrace(); // 打印堆栈跟踪信息
}
}
private static String readFile(File file) throws IOException {
if (!file.exists()) {
throw new FileNotFoundException(file.getAbsolutePath() + " does not exist"));
}
try (BufferedReader br = new BufferedReader(new FileReader(file)))) {
return br.readLine();
}
}
}
这里处理了读取文件时可能遇到的`FileNotFoundException`。
2. 网络请求:
```java
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetworkRequest {
public static void main(String[] args) {
try {
// 发送GET请求
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
System.out.println(connection.getInputStream().readAllBytes()));
} else {
System.err.println("Error occurred during GET request: " + responseCode);
}
} catch (ConnectException ce, IOException ioe) {
// 处理连接异常和IO异常
System.err.println("Error occurred while making network connection: "
+ (ce != null ? ce.getMessage() : "Unknown error")));
if (ioe != null) {
System.err.println("Additional I/O error occurred: " + ioe.getMessage());
}
}
}
}
这里处理了在发送网络请求时可能出现的ConnectException
和IOException
。
总结,通过理解和使用try-catch-finally
语句块,Java程序员可以更好地应对各种异常情况,并确保程序的稳定性和健壮性。
还没有评论,来说两句吧...