使用try-catch捕获异常时,将可能出错的代码放入try块,用catch块处理特定异常。例如数组越界:try { int[] arr = new int[5]; System.out.println(arr[10]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("发生数组越界:" + e.getMessage()); e.printStackTrace(); }。可使用多个catch捕获不同异常,子类异常需优先声明。通过e.getMessage()获取异常描述,e.printStackTrace()打印堆栈信息,e.toString()返回异常类型与消息。可用catch(Exception e)捕获所有Exception类异常,但不包括Error。合理处理异常有助于排查问题,提升程序健壮性,避免忽略异常。

在Java中,使用catch捕获异常信息主要通过try-catch语句块实现。当程序可能发生异常时,将相关代码放入try块中,然后用一个或多个catch块来处理不同类型的异常。每个catch块可以捕获特定类型的异常,并获取异常的详细信息。
以下是使用try-catch捕获异常的基本格式:
try {
// 可能出现异常的代码
} catch (ExceptionType e) {
// 处理异常,e 是异常对象
}
例如,处理数组越界异常:
try {
int[] arr = new int[5];
System.out.println(arr[10]); // 抛出 ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("发生数组越界:" + e.getMessage());
e.printStackTrace(); // 打印完整的堆栈信息
}
一个try块可以对应多个catch块,用于处理不同类型的异常。子类异常要放在前面,避免被父类捕获覆盖。
立即学习“Java免费学习笔记(深入)”;
try {
int result = 10 / Integer.parseInt("0"); // 可能发生 NumberFormatException 或 ArithmeticException
} catch (NumberFormatException e) {
System.out.println("数字格式错误:" + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("算术异常:" + e.getMessage());
}
在catch块中,可以通过异常对象调用以下常用方法获取详细信息:
示例:
try {
throw new IllegalArgumentException("参数不合法");
} catch (IllegalArgumentException e) {
System.out.println("异常信息: " + e.getMessage());
System.out.println("异常类型: " + e.toString());
e.printStackTrace();
}
如果想统一处理所有异常,可以用catch (Exception e),但要注意它不会捕获Error类及其子类(如OutOfMemoryError)。
try {
// 可能抛出各种异常的代码
} catch (Exception e) {
System.out.println("发生未知异常:" + e.getMessage());
e.printStackTrace();
}
基本上就这些。合理使用catch并输出异常信息,有助于快速排查问题,提升程序健壮性。注意不要忽略异常,至少应记录日志或提示用户。
以上就是在Java中如何使用catch捕获异常信息的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号