IDEA Debug 时模拟抛出异常

IDEA Debug About 746 words

场景

需要测试代码异常情况,运行时模拟抛出异常。

比如模拟OutOfMemoryError内存溢出OOM异常等。

需要测试Spring全局的ControllerAdvice可以使用这个方法。

测试代码

断点打在System.out.println("aaa");该行。

public class MockThrowExceptionDemo {

    public static void main(String[] args) {
        System.out.println(mockThrowException());
    }

    public static String mockThrowException() {
        System.out.println("aaa");
        return "ok";
    }

}

步骤

  1. DebuggerFrames断点停顿处,右键运行的方法,点击Throw Exception
  2. 弹出对话框,输入需要模拟抛出的异常,比如RuntimeException,再点击OK
  3. 此时程序会跳转到Thread类中的dispatchUncaughtException这个方法,直接点击放行。(示例代码未使用try...catch捕获异常,所以会跳转到dispatchUncaughtException方法,反之需要多次点击Throw Exception,直到进入catch代码块)
  4. 此时控制台输出异常信息。

示意图

IDEA Debug Throw Exception.png

相关视频

https://www.bilibili.com/video/BV1ug411C7zr

https://www.ixigua.com/7131734345924116996

Views: 3,852 · Posted: 2022-08-07

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh