Java 异常处理入门
在编程世界中,错误是不可避免的。它们可能由多种原因引起:用户输入错误、文件不可用、程序逻辑错误或网络故障。在 Java 语言中,有一种强大而灵活的机制来管理此类情况——异常。正确的错误处理不仅是良好的编程习惯,更是应用程序稳定性、可靠性和安全性的保障。
本文将深入探讨 Java 中的错误处理机制,从基本的 try/catch 结构开始,一直讲到高级技术如 try-with-resources 和自定义异常的创建。您将了解已检查异常与未检查异常的区别,以及如何正确使用它们。
基础:try/catch 与 finally 结构
try 和 catch 块
Java 异常处理的核心是 try/catch 结构。可能引发异常的代码被放置在一个 try 块中。如果该块中发生异常,执行将立即转移到相应的 catch 块中进行处理。
public class Main { public static void main(String[] args) { try { int result = 10 / 0; // 这将引发 ArithmeticException System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Error: division by zero!"); e.printStackTrace(); // 打印调用堆栈以便调试 } System.out.println("Program continues..."); }}注意:System.out.println("Result: " + result); 这行代码不会执行,因为异常在此之前就发生了。但程序不会"崩溃"——控制权将转移到 catch 块,并且执行会在 try/catch 块之后继续。
多个 catch 块
一个 try 块可以有多个 catch 块来处理不同类型的异常。请务必记住,更具体的异常必须列在更通用的异常之前。
try { String str = null; System.out.println(str.length()); // NullPointerException int[] arr = new int[5]; arr[10] = 100; // ArrayIndexOutOfBoundsException} catch (NullPointerException e) { System.out.println("NullPointerException: " + e.getMessage());} catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException: " + e.getMessage());} catch (Exception e) { // 所有其他异常的通用处理器 System.out.println("General error: " + e.getMessage());}finally 块
finally 块是一个特殊的块,它总是会执行,无论是否抛出了异常。它非常适合用于释放资源:关闭文件、数据库连接或套接字。
import java.io.*;
public class FileExample { public static void main(String[] args) { FileInputStream file = null; try { file = new FileInputStream("test.txt"); int data = file.read(); System.out.println((char) data); } catch (FileNotFoundException e) { System.out.println("File not found!"); } catch (IOException e) { System.out.println("Input/output error!"); } finally { try { if (file != null) { file.close(); // 在任何情况下都关闭文件 } } catch (IOException e) { System.out.println("Error closing the file!"); } } }}即使在 try 或 catch 块中发生了异常,finally 块仍然会执行。