Debugging Given a failure, find and fix the error. Key is reproducibility What input causes the failure? 1 Debugging Strategies Goal: Find a point in your program where it behaves differently than what you expect. Work backwards to the error. assert calls Output statements within System.out.println Use a debugger. 2 Debugger Set a breakpoint to pause execution. View variable values while paused. Continue execution by: Continuing to the next breakpoint Stepping to the next statement in the method Stepping into a method being called 3 Wednesday, February 13, 13
Breakpoints Line of code where execution should pause so that you can look at the values of variables To set a breakpoint in Eclipse, double-click in the margin to the left of the line where you want to stop A blue dot will appear in the margin 4 Running the Debugger Click on the bug icon rather than the play button Execution pauses when reach breakpoint, showing an arrow where the execution has stopped 5 Eclipse Debug Perspective Execution Call Stack Variables Controls 6 Wednesday, February 13, 13
Execution Controls Stop Execution Step Into Step Over Continue Stop when current method returns 7 Variables 8 Call Stack 9 Wednesday, February 13, 13
Reading Stack Traces Focus on the top 10 Reading Stack Traces Where the failure occurred Nature of the failure 11 NullPointerException Means a variable has been used before it was set. � private ImageIcon snow; � � public SnowFlake(ImageIcon snow, int left, int screenHeight, int fallOffset) { � � super(-snow.getIconHeight(), screenHeight, fallOffset); � � this.left = left; � � this.top = -snow.getIconHeight(); � } � � public void paint (JComponent component, Graphics g) { � � snow.paintIcon(component, g, left, top); � } 12 Wednesday, February 13, 13
NullPointerException Means a variable has been used before it was set. � private ImageIcon snow; � � public SnowFlake(ImageIcon snowIcon, int left, int screenHeight, int fallOffset) { � � super(-snow.getIconHeight(), screenHeight, fallOffset); ImageIcon snow = snowIcon; � � this.left = left; � � this.top = -snow.getIconHeight(); � } � � public void paint (JComponent component, Graphics g) { � � snow.paintIcon(component, g, left, top); � } 13 Another Stack Trace Notice that your method is not at the top of the stack. Means you are passing null as a parameter value snow.paintIcon(component, g, left, top); Either component or g must be null. 14 Other Common Exceptions ArrayIndexOutOfBoundsException - negative value, or value too big ClassCastException - attempting to cast to something of the wrong type Polygon p = new Rectangle(); OK Rectangle r = (Rectangle) p; Circle e = (Circle) p; ClassCastException 15 Wednesday, February 13, 13
Recommend
More recommend