例外是程序执行期间发生的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的行之后的代码将永远不会执行。
在Java 7之前,只要我们有一个可能会生成多个异常的代码,并且如果您需要专门处理该代码,则应在一次尝试中使用多个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 a number with 0"); } } }
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
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 a number with 0
从Java 7开始,使用此功能引入了Multicatch块,您可以在单个catch块中处理多个异常。
在此,您需要指定所有要处理的异常类,并用“ | |”分隔。”,如下所示-
catch(ArrayIndexOutOfBoundsException | ArithmeticException exp) { System.out.println("Warning: Enter inputs as per instructions "); }
以下Java程序演示了Multicatch的用法。在这里,我们在单个catch块中处理所有异常。
import java.util.Arrays; import java.util.Scanner; public class MultiCatch { 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 | ArithmeticException exp) { System.out.println("Warning: Enter inputs as per instructions "); } } }
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) 0 9 Warning: Enter inputs as per instructions
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 4 Warning: Enter inputs as per instructions