Java异常处理与捕获示例
在Java中,异常是程序运行时出现的错误情况。通过异常处理和捕获,我们可以优雅地处理这些错误。
以下是一个简单的异常处理和捕获的例子:
public class ExceptionHandlingExample {
public static void main(String[] args) {
// 尝试访问一个不存在的数组元素
try {
int[] array = {1, 2, 3};
System.out.println(array[4]); // 这将抛出ArrayIndexOutOfBoundsException异常
} catch (ArrayIndexOutOfBoundsException e) {
// 捕获到异常后,我们可以在这里处理它
System.out.println("Error: Index out of bounds. " + e.getMessage());
}
}
}
在这个例子中,我们尝试访问一个不存在的数组元素。这自然会导致ArrayIndexOutOfBoundsException
异常。通过try-catch
结构,我们成功捕获了这个异常,并在catch
块中处理它。
还没有评论,来说两句吧...