一个try块在Java中可以有多个catch块吗?
是的,单个try块可以有多个catch块。
示例
以下Java程序包含一个数字数组(显示)。从用户那里,它接受此数组中的两个位置,然后将第一个位置的数字除以第二个位置的数字。
输入值时-
如果选择的位置不在显示的数组中,则抛出ArrayIndexOutOfBoundsException
如果选择0作为分母,则抛出ArithmeticException。
在此程序中,我们使用两个不同的catch块处理了所有可能的异常。
import java.util.Arrays;
import java.util.Scanner;
public class MultipleCatchBlocks {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Enter 3 integer values one by one: ");
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Warning: You have chosen a position which is not in the array");
}
catch(ArithmeticException e) {
System.out.println("Warning: You cannot divide an number with 0");
}
}
}输出1
Enter 3 integer values one by one: Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator (not 0) from this array (enter positions 0 to 5) 2 8 Warning: You have chosen a position which is not in the array
输出2
Enter 3 integer values one by one: Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator(not 0) from this array (enter positions 0 to 5) 1 4 Warning: You cannot divide an number with 0
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿