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";
}
}
步骤
Debugger的Frames断点停顿处,右键运行的方法,点击Throw Exception。- 弹出对话框,输入需要模拟抛出的异常,比如
RuntimeException,再点击OK。 - 此时程序会跳转到
Thread类中的dispatchUncaughtException这个方法,直接点击放行。(示例代码未使用try...catch捕获异常,所以会跳转到dispatchUncaughtException方法,反之需要多次点击Throw Exception,直到进入catch代码块) - 此时控制台输出异常信息。
示意图

相关视频
Views: 6,996 · Posted: 2022-08-07
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...