0% found this document useful (0 votes)
3 views37 pages

CENG325 9 Debugging

The document provides an overview of debugging in Java, including definitions, good programming practices, and methods for debugging using tools like NetBeans. It covers exception handling with try/catch blocks and categorizes exceptions into checked, unchecked, and errors. The document emphasizes the importance of proper coding practices to minimize debugging needs and offers examples to illustrate debugging techniques and exception handling.

Uploaded by

42330003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

CENG325 9 Debugging

The document provides an overview of debugging in Java, including definitions, good programming practices, and methods for debugging using tools like NetBeans. It covers exception handling with try/catch blocks and categorizes exceptions into checked, unchecked, and errors. The document emphasizes the importance of proper coding practices to minimize debugging needs and offers examples to illustrate debugging techniques and exception handling.

Uploaded by

42330003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Debugging of a Java Program

1
Content
 Definition
 Good Programming Practices
 Basic Debugging, printout messages
 Advanced Debugging: Netbeans
Debugger
 Exception Handling Try/Catch
 Types of exceptions with examples

2
Debugging Definition
 The process of detecting and removing of existing and
potential errors (also called as ‘bugs’) in a software code that
can cause it to behave unexpectedly or crash.
 Types of errors:
 Easy to catch errors (e.g. syntax) that are taken care of by the
compiler (underlined in red with a hint message aside )
 Quickly identified error by looking at the exception message given
in the output
 However, there are errors which can be very tricky and take really
long to find and fix!

 Sometimes it takes more time to debug a program than to


code it!

 With good programming practice, debugging in most cases


might become unnecessary!
3
Content
 Definition
 Good Programming Practices
 Basic Debugging, printout messages
 Advanced Debugging: Netbeans
Debugger
 Exception Handling Try/Catch
 Types of exceptions with examples

4
Good programming practices
 Commenting:
 Start your program with a comment explaining the main
purpose of the program/class.
 Next to each line, or method, insert a comment to explain
what the line of code is trying to achieve.
 Good commenting not only helps another programmer read
and understand your code, it would also allow you to detect
your own mistakes and remember your code objectives

 Naming conventions:
 Choose meaningful names for your variables, classes and
methods.
 Good names facilitate the process of debugging and make
your code more portable and understandable for later use or
for other programmers.

5
Good programming practices
 Modular Programming (use functions):
 A procedure that is repeated several times in your
code  create a method with a meaningful name
 Easier for read your code later and also easier to
debug your program.

 Try/Catch blocks:
 Java offers an elegant way to catch all the exceptions
that might happen in your code.
 By using Try/catch block, errors are caught during
runtime and can be explicitly handled not to interrupt
the course of the program.
 There are many types of exceptions (to be seen later).

6
Learn by Example: Summation
program

7
Program output

• i=7 was not printed and we got an error. This is due to the fact that
the for loop has reached the character ‘a’ which is not an integer.

• This is why, you get a NumberFormatException

• The execution is interrupted and the final sum was not displayed.

8
Content
 Definition
 Good Programming Practices
 Basic Debugging, printout messages
 Advanced Debugging: Netbeans
Debugger
 Exception Handling Try/Catch
 Types of exceptions with examples

9
Basic debugging: printout messages
 The simplest way to debug a program is to printout some
messages here and there in the code to follow up its execution
thread.
 E.g. In the previous example: Output the character to the screen
and its index before trying to convert to integer.

Ou
tp
ut
10
Basic debugging: shortage
 Littering your code with System.out.println here and
there to detect any buggy performance might seem
an easy idea for small codes!

 it’s totally inconvenient and time waster for big codes.

 this is not always evident to figure out errors using


system printout!

 Plus, the messages are only used for debugging


purposes and must be removed.

11
Content
 Definition
 Good Programming Practices
 Basic Debugging, printout messages
 Advanced Debugging: Netbeans
Debugger
 Exception Handling Try/Catch
 Types of exceptions with examples

12
Advanced Debugging: NetBeans
Debugger
 IDEs (NetBeans in our case) usually provide user with a
debugger option
 The debugger is a powerful tool to find bugs by providing
an insight into the internal operations of a program.

 This is possible by pausing the execution by breakpoints.

 Then, analyzing the state of the program (examine


variables and how they are changed line by line)

 The breakpoints are stored in the IDE (NetBeans) and not


in the code.

13
Learn by Example: SumSquare prog.

14
1- Set/Remove a BreakPoint
 A breakpoint: a mark in the source code that indicates
the debugger to stop when the execution reach it.
 When your program stops on a breakpoint, you can
inspect the current values of the variables in your
program or continue the execution of your program,
one line at a time.

 To set a breakpoint, click on the left margin (in grey)


on the line where you want to place the breakpoint.
 NetBeans highlights the line in red with a red mark on
the left margin.
15
2. Monitor variable value
 Two methods to monitor the values of variables or
expressions during program execution:

 Method1: hover the mouse over the variable.


 the debugger will display the value of the variable close to
where the cursor is placed.

 Method 2: adding a watch on the variable.


 select the variable or expression you want to monitor
 From the Debug menu, click on new watch  watch any
variable you want.
 Windows àà Debugging àà watches (to show watches)

16
3. Start Debugging
Several ways to execute a java program in debug
mode:

 Debug Main Project in the Debug menu to execute the


program to the first breakpoint.
 If you did not set a breakpoint, the program will run until it
terminates.

 Step Into in the Debug menu to run the program to the first
line of the main method.

 Run to Cursor in the Debug menu to execute run program


until the line in the source code where the cursor is currently
located.

17
Debugging SumSequare prog.
 Debug Main project in the Debug menu.
 Program runs and stops at the line where the
breakpoint is set and the color becomes
green.

 The line with the breakpoint is not executed.

 Check the variables and watches tabs at the


bottom. The values for a,b and result haven’t
been assigned yet.

18
Debugging options
 Step Over ( - F8) - Executes one line of code.
 If the line is a call to a method, executes the method
without stepping into the method's code.

 Step Into ( - F7)- Executes one line of code.


 If the line is a call to a method, step into the method
and stop on the first line of the method.

 Step Out ( CTRL+F7) - Executes one line of


code.
 if the source code line is in a method, it will execute
the remaining source code in the method and returns
to the caller of the method.
19
Attempt 1: use the step over.
 Click on step over, and monitor the watches and
variables.

 Notice that only d.a has a value since the


debugger has executed this line and now is
waiting at the next line.

 Keep clicking on step over and monitoring the


values. You will see that the method is executed
in 1 step and the D.result is filled.

20
Attempt 2: use the step into
 Stop the debugger and run it again. Again, the
debugger will stop at the breakpoint. Now,
click on step into and monitor the variables.

 When the debugger reaches the method call,


notice that it will jump to inside the method
code.

21
End Debugging
 To end the debugger session, click on
Finish Debugger Session in the Debug
menu.

22
Content
 Definition
 Good Programming Practices
 Basic Debugging, printout messages
 Advanced Debugging: Netbeans
Debugger
 Exception Handling Try/Catch
 Exceptions categories with
examples

23
Exception Definition
 An exception: is a problem (unwanted event) that
arises during the execution of a program.

 When an Exception occurs, the normal flow of the


program is interrupted.
 The program terminates abnormally (not recommended!)

 exceptions are to be handled 


 the flow of the program doesn’t break (program is not
terminated)
 provide a meaningful message to the user about the
caught error.

24
Reasons for exceptions
Scenarios in which an exception occurs:

 A user has entered an invalid data.


 A file that needs to be opened cannot be found.
 A program that accesses beyond the boundaries of an
array.
 A division by 0 operation
 A number parsing of a String variable.
 Etc.

Some of these exceptions are caused by user error, others


by programmer error, and others by physical resources that
have failed in some manner (A network connection has
been lost).
25
Content
 Definition
 Good Programming Practices
 Basic Debugging, printout messages
 Advanced Debugging: Netbeans
Debugger
 Exception Handling Try/Catch
 Exceptions categories with
examples

26
Exception Categories

Exceptions can be categorized into :

 Checked exceptions
 Unchecked exceptions
 Errors

27
Checked exceptions
 An exception that is checked (notified) by the
compiler at compilation-time.

 It cannot simply be ignored, or the program


might not run!

 E.g. FileReader in your program to read data


from a file that does not exist 
a FileNotFoundException occurs, and the
compiler prompts the programmer to handle
the exception.

28
Checked Exception example

Ou
tp
ut
Note − Since the methods read() and close() of FileReader class throws
IOException  the compiler notifies to handle IOException, along with
FileNotFoundException.

29
Unchecked exceptions (Runtime
exceptions)
 An exception that occurs at the time of
execution.

 Runtime exceptions are ignored at the time of


compilation.
 E.g. if you have declared an array of size 5 in
your program, and trying to call the
6th element of the array then
an ArrayIndexOutOfBoundsExceptionexceptio
n occurs.

Ou
tp
ut
30
Errors
 These are not exceptions at all, but problems
that arise beyond the control of the user or
the programmer.

 Errors are typically ignored in your code


because you can rarely do anything about an
error.

 For example, if a stack overflow occurs, an


error will arise.

 They are also ignored at the time of


31
compilation.
Exceptions and Errors hierarchy
 All exception and errors types are sub classes of
class Throwable (more info about exceptions in
CSCI300)

32
Handling Exceptions: Try/Catch method
 Java handle exceptions by using a combination of
the try and catch keywords.
 A try/catch block is placed around the code that
might generate an exception.
try {
// Protected code
} catch (ExceptionType e) {
// Catch block
}

 The code that is exposed to exceptions is placed in


the try block (protected block).
 When an exception occurs, it is handled by a catch
block that is associated to it.
 Every try block should be immediately followed
either by a catch block or finally block.
33
Catch block
 A try block can be followed by multiple catch blocks.
 If an exception occurs in the protected code, the
exception is thrown to the first catch block in the list.
 If the data type of the exception thrown matches
ExceptionType1, it gets caught there.
 If not, the exception passes down to the second catch
statement and so on.
 A generic catch block can handle all the exceptions
(Exception e).
 Attention: with generic exception handler you are
not sure for which type of exception it may trigger
(same message for all exception types)

34
Finally block
 The finally block follows a try block or a catch
block.
 A finally block of code always executes,
irrespective of occurrence of an Exception.
 Using a finally block allows you to run any
cleanup-type statements that you want to
execute,
try { no matter what happens in the
protected code. code
// Protected
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
}finally {
// The finally block always executes.
35 }
Learn by Example: Summation program
• We will add another mistake to the first string summation programmer.
• Modify your code so it looks like the following. Note the <= in the for
loop (access beyond the bounds of the string (outOfBound)).

36
Output

By handling exceptions
 We can visualize and customize the way we detect errors
 We allow the program to continue normally (not to be interrupted).
 Catch block can be controlled to end the program as well.

37

You might also like