断点调试技巧

346 阅读4分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

调试常用快捷键

Step Over:单步调试,从断点行开始逐行向下执行,不会进入方法

Step Into:单步调试,从断点行开始逐行向下执行,会进入方法,但不会进入jdk的方法(rt.jar...)

Force Step Into:单步调试,强制进入方法,包括jdk里的方法,适合用来debug源码

Step Out:跳出方法,光标指向方法调用的下一行

Resume Program:跳到下一个断点

Drop Frame:关闭当前方法栈,回到上一个方法栈

debug时光标移动到变量处即可查看变量的当前值,也可在控制台里查看Variables

一、行断点

 这个是调试中最基础也是用得最多的调试方式。只需要在代码行号鼠标左键点击一下即可,完成后在行号旁即可看到一个红色的圆点。

image-20220818200904251.png

Debug模式运行main(),即可进入断点处。快捷键F6(单步执行,跳到下一行) ;快捷键F9(跳到下一个断点)

二、详细断点(源断点)

 在代码行号按住Shift+鼠标左键即可,此时出现黄色的小圆点,在弹出窗中选中Enabled,此时Debug模式运行程序并不会在断点行停止,但会在控制台里输出断点的详细信息;如果同时选中Suspend,选择All则会停止,而选择Thread则运行到当前线程才会停止(此选项适合多线程下的调试)

image-20220818201320017.png

image-20220818202008397.png

三、方法断点

 在方法第一行旁点击鼠标左键即可,可以看到出现菱形小红点。

image-20220818202331249.png

Debug模式运行方法时,则会首先进入方法第一行,快捷键跳到下一个断点则会进入当前方法的最后一行,此时可以看到此方法中所有变量的值。

image-20220818202640907.png

四、接口跳转实现类

 在定义接口的时候,如果我们创建实现类有多个,此时我们不仅可以在具体的实现类方法上打断点,也可以直接在接口的方法上打断点

image-20220818212010835.png

image-20220818212030789.png

Dog、Cat均为Animal的实现类,此时当我们Debug模式运行时,单步调试进入到具体的实现方法里,这样更便于我们找到接口的实现类,特别是调用第三方的包,此调试方式的优势格外明显,这样就不用我们一个个去找实现类再加断点了。

image-20220818212420635.png

image-20220818212441825.png

五、异常断点

 在BreakPoint Views窗口Ctrl+Shift+F8里,定义我们需要全局捕获的异常,不管程序运行到哪里,当异常出现的时候,则会自动进入异常处。如常见的空指针异常等。

image-20220818212830240.png

点击左上角“+”可以添加任何异常,可以搜索异常(包括自定义的异常),支持模糊匹配,Debug时只要出现需要捕获的异常,则会自动进入异常出现行,方便我们定位异常出现的地方,同时可以看到当前变量的值。

image-20220818213016485.png

红色闪电即表示需要捕获的异常出现了。

image-20220818213426167.png

六、字段监控

 在类的属性字段上打上断点后,Debug模式运行时我们就可以看到这个变量的变化过程,每次变量修改时都会进入到参数修改的方法上。方便我们对字段进行监控,即字段什么时候被什么方法修改了,改成了什么。

image-20220818214449410.png

image-20220818214515013.png

附上源码:

public class BreakPointTest {

//行断点
public static void line() {
System.out.println("this is the line break point");
}

//详细断点 (也叫源断点)
public static void detailLine() {
System.out.println("this is the detail line break point");
}

//方法断点  | 接口跳转实现类
public static void method() {
HelloController helloController = new HelloController();
String response = helloController.hello();
System.out.println(response);
System.out.println("this is from method");
}

public static void implementmethod() {
Animal dog = new Dog();
dog.action();
Animal cat = new Cat();
cat.action();

}

// 异常断点 | 全局捕获
public static void exception() {
Object o = null;
o.toString();
System.out.println("this is the line break point");
}

// 字段断点  | 读写监控
public static void field() {
Person person = new Person();
person.setId(12);
System.out.println(person);
}

public static void main(String[] args) {
//        line();
//        detailLine();
//        method();
//        implementmethod();
//        exception();
field();
}
}

public interface Animal {
public void action();
}

public class Dog implements Animal {
@Override
public void action() {
System.out.println("汪汪汪");
}
}

public class Cat implements Animal {
@Override
public void action() {
System.out.println("喵喵喵");
}
}