Java异常处理机制及常见场景实例

原创 我就是我 2025-03-15 11:09 17阅读 0赞

Java的异常处理机制主要通过try-catch-finally结构实现。

  1. try块:包含可能抛出异常的代码。如果在try块中发生任何异常,Java将停止执行try块后面的代码,并立即跳转到最近的catchfinally块。

  2. catch块(可选):用于捕获并处理特定类型的异常。只有当try块中的异常被声明为该catch块的类型时,才会匹配并执行。

  3. finally块(可选):无论是否发生异常,都会执行的代码块。常用来释放资源或清理工作等。

以下是一些常见场景实例:

  1. 文件读写操作:

    1. try {
    2. File file = new File("example.txt");
    3. if (!file.exists()) { throw new FileNotFoundException("File not found"); }
    4. // 读取文件
    5. String content = new Scanner(file).useDelimiter("\\A").next();
    6. System.out.println(content);
    7. // 写入文件
    8. file.createNewFile();
    9. writer = new PrintWriter(file);
    10. writer.print("Updated content.");
    11. writer.close();
    12. } catch (FileNotFoundException e) {
    13. System.err.println(e.getMessage());
    14. }
  2. 网络请求:
    ```java
    import java.net.HttpURLConnection;
    import java.net.URL;

try {
URL url = new URL(“https://api.example.com/data“);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

  1. // 设置请求方法和超时时间
  2. connection.setRequestMethod("GET");
  3. connection.setConnectTimeout(1000); // 1秒
  4. int responseCode = connection.getResponseCode();
  5. System.out.println("Response Code: " + responseCode);
  6. // 获取响应内容并处理
  7. if (responseCode == HttpURLConnection.HTTP_OK) {
  8. String content = new String(connection.getInputStream()));
  9. System.out.println(content);
  10. }

} catch (Exception e) {
System.err.println(e.getMessage());
}
```
总之,Java的异常处理机制允许我们优雅地捕获和处理程序运行时可能出现的问题。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,17人围观)

还没有评论,来说两句吧...

相关阅读