异常捕获抛出,循环中捕获抛出,程序和循环是否继续运行?

本文详细讨论了Java中在循环结构中如何处理异常,包括不处理、捕获于循环内部、循环外部以及仅抛出的情况,强调了try-catch对异常流程的影响和不同位置的处理效果。

问题

异常之后程序的运行情况,如果在循环中,不同的处理异常方式,程序是结束?继续?循环是继续?还是跳过?

结论

  • 有捕获异常的程序可以继续执行,但是从异常代码这行开始直到try结束都不执行,出了try再继续执行
  • 没捕获异常,就直接报错,不论是否抛出(不考虑抛出后在其他方法中进行捕获)
  • 根据以上结论得出:如果是for-try,那么for可以完成全部循环,但是出异常的那次循环从异常代码那一行开始后面的就不执行了,直接进行下一次循环。如果是try-for,那么一个单独的for相当于没有捕获异常,for运行到异常后会直接中断,程序跳到try外面继续执行。而throws相当于什么都没干,继续传递异常等待调用它的方法去处理。

测试

不处理,循环内/外捕获,仅抛出,循环内捕获中抛出,循环外捕获中抛出…

不处理

异常结束,异常后的代码不执行

    /**
     * 出现异常什么都不做
     */
    public void nothing(){

        System.out.println("异常开始前");
        for (int i = 0; i < 5; i++){
            System.out.println("i = " + i);
            if(i == 2){
                System.out.println("出现异常...");
                int j = 10 / 0;
                System.out.println("异常的下一行...");
            }
        }
        System.out.println("异常结束后");

    }
------------什么都不做----------
异常开始前
i = 0
i = 1
i = 2
出现异常...
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at org.example.other.TryCatchAfterSomethings.nothing(TryCatchAfterSomethings.java:19)
	at org.example.App.main(App.java:45)

Process finished with exit code 1

捕获-循环内

正常结束,for全部执行。但是for-try中异常后面的代码不会执行,抛出异常后,下一个循环正常运行

    /**
     * 捕获异常,try放在循环内
     */
    public void catchExceptionInFor(){
        System.out.println("异常开始前");
        for (int i = 0; i < 5; i++){
            System.out.println("i = " + i);
            if(i == 2){
                try {
                    System.out.println("出现异常...");
                    int j = 10 / 0;
                    System.out.println("异常的下一行...");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        System.out.println("异常结束后");
    }
------------捕获异常,try放在循环内----------
异常开始前
i = 0
i = 1
i = 2
出现异常...
i = 3
i = 4
异常结束后
java.lang.ArithmeticException: / by zero
	at org.example.other.TryCatchAfterSomethings.catchExceptionInFor(TryCatchAfterSomethings.java:36)
	at org.example.App.main(App.java:47)
	
Process finished with exit code 0

捕获-循环外

正常结束,for中断执行,但程序全部执行。try-for中异常触发,不会被处理,在try中异常后剩余代码不会执行,但出了try后继续执行

    /**
     * 捕获异常,异常放在循环外
     */
    public void catchExceptionOutFor(){

        System.out.println("异常开始前");
        try {
            for (int i = 0; i < 5; i++){
                System.out.println("i = " + i);
                if(i == 2){
                    System.out.println("出现异常...");
                    int j = 10 / 0;
                    System.out.println("异常的下一行...");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("异常结束后");
    }
------------捕获异常,try放在循环外----------
异常开始前
i = 0
i = 1
i = 2
出现异常...
异常结束后
java.lang.ArithmeticException: / by zero
	at org.example.other.TryCatchAfterSomethings.catchExceptionOutFor(TryCatchAfterSomethings.java:58)
	at org.example.App.main(App.java:51)

Process finished with exit code 0

仅抛出

异常结束,for中断执行。异常后的代码不执行,不考虑在调用时捕获的问题

    /**
     * 只抛出异常,不捕获,循环内
     */
    public void throwException() throws Exception {
        System.out.println("异常开始前");
        for (int i = 0; i < 5; i++){
            System.out.println("i = " + i);
            if(i == 2){
                System.out.println("出现异常...");
                throw new Exception();
                // throw后的代码直接提示报错
                // System.out.println("异常的下一行...");
            }
        }
        System.out.println("异常结束后");
    }
------------只抛出异常,不捕获,循环内----------
异常开始前
i = 0
i = 1
i = 2
出现异常...
Exception in thread "main" java.lang.Exception
	at org.example.other.TryCatchAfterSomethings.throwException(TryCatchAfterSomethings.java:79)
	at org.example.App.main(App.java:54)

Process finished with exit code 1

抛出-循环内-捕获

正常结束,for全部执行。for-try-throw后不能写代码,所以抛出throw后的代码不执行,下一个循环正常运行,捕获之后方法上的throws Exception失效

    /**
     * 抛出异常,并捕获,在循环内
     */
    public void throwAndCatchExceptionInFor() throws Exception {
        System.out.println("异常开始前");
        for (int i = 0; i < 5; i++){
            System.out.println("i = " + i);
            if(i == 2){
                try {
                    System.out.println("出现异常...");
                    throw new Exception();
                    // throw后的代码直接提示报错
                    // System.out.println("异常的下一行...");
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
        System.out.println("异常结束后");
    }
------------抛出异常,并捕获,在循环内----------
异常开始前
i = 0
i = 1
i = 2
出现异常...
i = 3
i = 4
异常结束后
java.lang.Exception
	at org.example.other.TryCatchAfterSomethings.throwAndCatchExceptionInFor(TryCatchAfterSomethings.java:97)
	at org.example.App.main(App.java:57)

Process finished with exit code 0

抛出-循环外-捕获

正常结束,for中断执行。try在for外面,所以for中异常一次就直接失败,但是try后面方法继续执行

    /**
     * 抛出异常,并捕获,在循环外
     */
    public void throwAndCatchExceptionOutFor() throws Exception {
        System.out.println("异常开始前");
        try {
            for (int i = 0; i < 5; i++){
                System.out.println("i = " + i);
                if(i == 2){
                    System.out.println("出现异常...");
                    throw new Exception();
                    // throw后的代码直接提示报错
                    // System.out.println("异常的下一行...");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        System.out.println("异常结束后");
    }
------------抛出异常,并捕获,在循环外----------
异常开始前
i = 0
i = 1
i = 2
出现异常...
异常结束后
java.lang.Exception
	at org.example.other.TryCatchAfterSomethings.throwAndCatchExceptionOutFor(TryCatchAfterSomethings.java:119)
	at org.example.App.main(App.java:60)

Process finished with exit code 0

如果内容有错误,还请指出,谢谢!

在C++中,抛出捕获运行异常是一种常见的错误处理机制,能够帮助开发者构建更健壮的应用程序。通过标准库中的`std::runtime_error`类,可以方便地抛出表示运行时错误的异常[^4]。 ### 抛出运行异常抛出一个运行异常,首先需要包含头文件`<stdexcept>`,然后创建一个`std::runtime_error`实例,并使用`throw`关键字抛出它。例如,当检测到一个不应该发生的条件时,可以抛出这样的异常: ```cpp #include <iostream> #include <stdexcept> void check_positive(int value) { if (value <= 0) { throw std::runtime_error("Value must be positive"); } } ``` 在这个例子中,如果传给`check_positive`函数的参数小于或等于零,函数将抛出一个带有错误消息的`std::runtime_error`异常[^4]。 ### 捕获运行异常 为了捕获并处理抛出异常,可以使用`try-catch`块。`try`块包围可能抛出异常的代码,而`catch`块用于捕获并处理异常。下面是一个完整的示例,演示了如何捕获上面抛出的`std::runtime_error`异常: ```cpp int main() { try { check_positive(-5); } catch (const std::runtime_error& e) { std::cerr << "Caught a runtime_error: " << e.what() << std::endl; } return 0; } ``` 在这个`main`函数中,调用了`check_positive`函数并传入了一个负数,这会触发异常抛出。由于这个调用是在`try`块内部进行的,因此可以被捕获到,并且通过`catch`块中的`e.what()`方法获取异常的具体错误信息,然后输出到标准错误流中。 ### 使用`std::throw_with_nested`进行嵌套异常处理 除了基本的异常抛出捕获之外,C++11还引入了`std::throw_with_nested``std::rethrow_if_nested`来支持嵌套异常的处理。这允许在一个异常捕获后,再次抛出一个新的异常,同时保留原始异常的信息。例如: ```cpp #include <exception> #include <stdexcept> #include <iostream> void func_a() { try { throw std::runtime_error("Original error"); } catch (...) { std::throw_with_nested(std::runtime_error("Nested error")); } } void func_b() { try { func_a(); } catch (...) { std::throw_with_nested(std::runtime_error("Another nested error")); } } int main() { try { func_b(); } catch (const std::exception& e) { std::cerr << "Caught exception: " << e.what() << std::endl; if (const auto* ne = dynamic_cast<const std::nested_exception*>(&e)) { try { ne->rethrow_nested(); } catch (const std::exception& inner) { std::cerr << "Inner exception: " << inner.what() << std::endl; } } } return 0; } ``` 在这个例子中,`func_a`抛出一个`std::runtime_error`异常,然后在捕获异常后,使用`std::throw_with_nested`抛出一个新的异常,同时保留了原始异常的信息。`func_b`重复了这一过程,最终在`main`函数中捕获最外层的异常,并通过`std::rethrow_if_nested`检查并重新抛出嵌套的异常,从而能够访问到所有层级的异常信息[^3]。 通过这种方式,C++提供了强大的异常处理机制,不仅可以处理简单的运行时错误,还能处理复杂的异常情况,包括嵌套异常,使得开发者能够更好地控制程序的行为,提高程序的健壮性可靠性。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值