Java异常处理:常见场景与案例

原创 Bertha 。 2024-09-24 02:15 378阅读 0赞

在Java编程中,异常处理是防止程序因意外情况而崩溃的重要机制。以下是一些常见的Java异常处理场景和案例:

  1. 文件操作

    • 检查文件是否存在:
      1. File file = new File("path/to/file.txt");
      2. if (!file.exists()) {
      3. throw new IllegalArgumentException("File does not exist.");
      4. }
    • 读写文件,捕获可能的IOException异常:

      1. BufferedReader br = null;
      2. try {
      3. br = new BufferedReader(new FileReader("file.txt")));
      4. // 读取内容
      5. String content = br.readLine();
      6. System.out.println(content);
      7. } catch (IOException e) {
      8. e.printStackTrace(); // 或者使用处理方式,如记录日志等
      9. if (br != null) {
      10. try {
      11. br.close();
      12. } catch (IOException ex) {
      13. ex.printStackTrace();
      14. }
      15. }
      16. throw new RuntimeException("Error reading file.", e);
      17. }
      18. finally {
      19. if (br != null) {
      20. try {
      21. br.close();
      22. } catch (IOException ex) {
      23. ex.printStackTrace();
      24. }
      25. // 确保文件关闭,即使发生异常
      26. }
      27. }
  2. 网络通信

    • 发送HTTP请求,捕获可能的Exception:

      1. try {
      2. URL url = new URL("http://example.com");
      3. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      4. connection.setRequestMethod("GET");
      5. int responseCode = connection.getResponseCode();
      6. if (responseCode == 200) {
      7. // 请求成功,读取响应内容
      8. BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
      9. String content = br.readLine();
      10. System.out.println(content);
      11. } else {
      12. // 请求失败或状态码不为200
      13. System.out.println("Request failed with response code " + responseCode));
      14. }
      15. } catch (Exception e) {
      16. e.printStackTrace(); // 或者使用处理方式,如记录日志等
      17. System.out.println("An error occurred during request execution.");
      18. }
  3. 数据库操作

    • 连接数据库,捕获可能的SQLException异常:

      1. Connection connection = null;
      2. try {
      3. // 创建连接对象
      4. Class.forName("com.mysql.jdbc.Driver");
      5. connection = DriverManager.getConnection(
      6. "jdbc:mysql://localhost:3306/mydatabase",
      7. "username",
      8. "password"
      9. );
      10. // 执行SQL语句
      11. Statement stmt = connection.createStatement();
      12. ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
      13. while (rs.next()) {
      14. // 处理查询结果
      15. int id = rs.getInt("id");
      16. String name = rs.getString("name");
      17. System.out.println("ID: " + id + ", Name: " + name);
      18. }
      19. } catch (Exception e) {
      20. e.printStackTrace();
      21. System.out.println("An error occurred while executing SQL queries.");
      22. } finally {
      23. if (connection != null) {
      24. try {
      25. connection.close();
      26. } catch (SQLException se) {
      27. se.printStackTrace();
      28. System.out.println("Error closing database connection.");
      29. }
      30. }
      31. }

以上例子展示了Java中处理不同异常情况的常见场景。在实际编程中,需要根据具体需求和异常类型进行相应的异常处理。

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

发表评论

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

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

相关阅读