在Java中,我们可以在处理已检查异常时抛出未检查异常吗?
当异常在catch块中被捕获时,您可以使用throw关键字(用于抛出异常对象)重新抛出它。
在重新抛出异常时,您可以原封不动地抛出相同的异常,无需对其进行调整,例如:
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArithmeticException e) {
throw e;
}或者,将其包装在一个新的异常中并抛出。当您将捕获的异常包装在另一个异常中并抛出时,这被称为异常链或异常包装,通过这样做,您可以调整您的异常,抛出更高级别的异常并保持抽象。
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
}从已检查异常抛出未检查异常
是的,我们可以捕获编译时异常(已检查)并在catch块中将其包装在运行时异常(未检查)中并重新抛出。但是,由于我们使用已检查异常重新抛出,因此我们需要将其包装在隐式try-catch对中,或者使用throws子句跳过处理它。
示例
在下面的Java示例中,我们创建了一个名为SampleException的用户定义(已检查)异常。
我们显示一个包含6个元素的整数数组,并允许用户选择两个值的索引并对选定的数字进行除法运算。在选择索引时,用户可能会使用超出数组长度的索引值,这会导致ArrayIndexOutOfBoundsException,这是一个未检查异常。
在catch块中,我们通过将其包装在上面创建的Sample异常(已检查)中来重新抛出此对象。
import java.util.Arrays;
import java.util.Scanner;
class SampleException extends Exception {
SampleException(String msg){
super(msg);
}
}
public class Rethrow {
public void demoMethod() {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 5, 8};
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) {
try {
throw new SampleException("This is a checked exception");
} catch (SampleException e1) {
System.out.println("Checked exception in the catch block");
}
}
}
public static void main(String [] args) {
new Rethrow().demoMethod();
}
}输出
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator(not 0) from this array (enter positions 0 to 5) 25 24 Checked exception in the catch block
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP