写一个捕获内置异常的程序: 数组下标越界异常ArrayIndexOutOfBoundsException和算术异常ArithmeticException,异常处理打印输出 “我是XXX异常”,异常统一出口打印输出“统一异常出口”
时间: 2024-03-04 21:05:26 浏览: 37
好的,以下是一个捕获内置异常的程序,包括数组下标越界异常和算术异常的处理:
```python
try:
# 数组下标越界异常
arr = [1, 2, 3]
print(arr[3])
except IndexError:
print("我是数组下标越界异常")
try:
# 算术异常
a = 1 / 0
except ZeroDivisionError:
print("我是算术异常")
finally:
print("统一异常出口")
```
输出结果为:
```
我是数组下标越界异常
我是算术异常
统一异常出口
```
相关问题
Java写一个捕获内置异常的程序: 数组下标越界异常ArrayIndexOutOfBoundsException和算术异常ArithmeticException,异常处理打印输出 “我是XXX异常”,异常统一出口打印输出“统一异常出口”
好的,以下是Java程序代码:
```
public class ExceptionDemo {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
try {
int result = nums[3]; // 数组下标越界异常
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("我是数组下标越界异常");
}
try {
int result = 10 / 0; // 算术异常
} catch (ArithmeticException e) {
System.out.println("我是算术异常");
} finally {
System.out.println("统一异常出口");
}
}
}
```
这个程序会抛出两种内置异常:数组下标越界异常和算术异常,分别在try-catch块中捕获并输出相应的异常信息,最后在finally块中输出“统一异常出口”。
输出一个数组的所有元素,捕获数组下标越界异常和除数为0异常
这是一个关于异常处理的编程问题,可以使用 try-catch 语句来捕获数组下标越界异常和除数为0异常。以下是一个示例代码,可以输出一个数组的所有元素并处理可能出现的异常:
```java
public class ArrayOutput {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
try {
for (int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界异常:" + e.getMessage());
}
try {
int a = 0;
int b = 10 / a;
System.out.println(b);
} catch (ArithmeticException e) {
System.out.println("除数为0异常:" + e.getMessage());
}
}
}
```
当数组下标越界或除数为0时,程序会捕获相应的异常并输出错误信息。如果没有出现异常,则可以正常输出数组的所有元素。