我知道并认识到(或者我认为是这样)通过 try{}catch block 处理异常和通过类或方法抛出异常之间的区别,但我想知道是否有办法通过方法使用throws
关键字,并在抛出异常后保留此代码/方法的执行?
我的意思是,就像下面的例子:
public class Main {
int[] array = {0,1,2};
public static void main(String[] args){
Main object = new Main();
System.out.println("Dealing inside try{}catch block");
object.dealInside();
System.out.println("Dealing by throws keyword");
try{
object.throwOutside();
}catch (ArrayIndexOutOfBoundsException ex){
}
}
public void dealInside(){
for(int i = 0; i < 6; i++){
try{
System.out.println(i);
int r = array[i];
}catch (ArrayIndexOutOfBoundsException ex){
}
}
}
public void throwOutside() throws ArrayIndexOutOfBoundsException{
for(int i = 0; i < 6; i++){
System.out.println(i);
int r = array[i];
}
}
}
如果循环中有try{}catch
block ,即使发生异常,方法也可以继续执行,并且即使数组的长度为3,它也会打印int最多6。但是万一一旦被中断的方法停止,抛出
异常的方法。
- 有没有办法继续该方法的工作,
抛出
异常(exception)吗? - 是否可以同时使用多种方法进行处理
它
抛出
类似/相同的异常,而不会中断 他们的处决?
最佳答案
终于
这就是finally
block 的确切用途。无论是否在其之前捕获到异常,都执行其中的代码。它总是会执行。
编写一些逻辑来通过改变finally block 内的i的值来实现你真正想要的。
try {
//risky code
} catch(Exception ex) {
//handle caught exception
} finally {
//this part always executes
}
现在,棘手的一点。如果您确实希望 for 循环继续进行,即使异常在后续语句中被捕获,您也可以这样做。
for(int i = 0; i < 6; i++) {
Thread t = new Thread(new Runnable() {
void run() {
try{
System.out.println(i);
int r = array[i];
}catch (ArrayIndexOutOfBoundsException ex){
}
});
t.start();
}
for 循环
在主线程
上运行,而有风险的代码则在单独的线程中运行。因此,即使遇到异常,主线程也会继续运行,因为它不知道抛出的异常。这是一个巧妙的技巧。但我不知道在实践中使用它是否是一个好主意。
关于java - 抛出异常而不中断方法的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31494926/