一个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