Java异常处理:捕获、处理和抛出示例

原创 ╰半橙微兮° 2024-12-05 08:54 117阅读 0赞

在Java中,异常是一种程序运行时可能出现的问题。通过异常处理机制,我们可以优雅地捕获、处理这些异常情况。

下面是一些基本的Java异常处理示例:

  1. 捕获并打印异常
  1. try {
  2. int divByZero = 5 / 0; // 这会抛出ArithmeticException
  3. } catch (ArithmeticException e) {
  4. System.out.println("Error: Division by zero caught.");
  5. e.printStackTrace(); // 打印堆栈跟踪信息,便于调试
  6. }
  1. 使用finally块进行资源清理
  1. try {
  2. File file = new File("non_existent_file.txt");
  3. FileReader reader = new FileReader(file);
  4. // 读取文件内容
  5. } catch (FileNotFoundException e) {
  6. System.out.println("Error: Could not find specified file.");
  7. e.printStackTrace();
  8. } finally {
  9. try {
  10. if (reader != null) {
  11. reader.close(); // 关闭资源,防止泄露
  12. }
  13. if (file != null && !file.delete()) {
  14. System.out.println("Warning: Failed to delete non-existent file.");
  15. }
  16. // 清理其他资源
  17. } catch (IOException ioe) {
  18. System.out.println("Error: Could not close or delete resources.");
  19. ioe.printStackTrace();
  20. }
  21. }

以上就是Java中异常处理的一些基本示例。在实际开发中,根据业务需求和异常类型进行更复杂的设计和处理。

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

发表评论

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

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

相关阅读