0% found this document useful (0 votes)
15 views60 pages

Day 09 - Debugging

xử lí lỗi trong java

Uploaded by

Thảo Phương
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views60 pages

Day 09 - Debugging

xử lí lỗi trong java

Uploaded by

Thảo Phương
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Debugging

Faculty of Information Technology, Hanoi University


What You Are About To Achieve 2
❖ By the end of this lecture, we are going to:
❑ Identify the different types of bugs in programming (Syntax, Runtime, and
Logic errors).
❑ Learn techniques for diagnosing and fixing bugs in code.
❑ Apply debugging tools to locate and resolve errors effectively.
❑ Develop strategies to prevent common coding errors in future projects.
❑ Practice debugging by solving real-world coding problems.
3
❖ Introduction to Bugs
❖ Syntax Errors
❖ Runtime Errors
❖ Logic Errors
❖ Exceptions Handling
❖ Debugging Strategies
❖ Final Touches
Introduction to Bugs 4
❖ When we say bugs - are you picturing those tiny, creepy critters crawling around in your
garden?
Introduction to Bugs 5
❖ Well, not quite! In the world of computer technology, bugs are something far more
troublesome
❖ A software bug is an error, vulnerability or malfunction that causes a program to behave
unpredictably. Think of it as a digital nuisance that disrupts the system, much like a
mosquito that buzzes around and is annoying. Bugs can range from minor glitches that
only slightly affect performance to serious problems that can crash entire systems. It's
like driving a car when the brakes suddenly fail - some bugs can be just as catastrophic.
Finding and fixing these bugs, known as debugging, is a kind of detective work where
you track down and fix these hidden problems before they cause damage. Every fixed
error brings the system closer to smooth, reliable operation and makes debugging an
important part of software development.
Fun fact: Did you know that one of the first ‘bugs’ was an actual moth stuck in a computer?
True story! Since then, developers have been swatting bugs both real and virtual!
Introduction to Bugs – Life Cycle 6
❖ And, like any bugs in your garden, these bugs also have a life cycle:
❑ New: When a defect is logged and posted for the first time. Its
state is given as new.
❑ Assigned: After the tester has posted the bug, the lead of the
tester approves that the bug is genuine and he assigns the bug to
corresponding developer and the developer team. Its state given
as assigned.
❑ Open: At this state the developer has started analyzing and
working on the defect fix.
❑ Fixed: When developer makes necessary code changes and
verifies the changes then he/she can make bug status as ‘Fixed’
and the bug is passed to testing team.
❑ Pending retest: After fixing the defect the developer has given
that particular code for retesting to the tester. Here the testing is
pending on the testers end. Hence its status is pending retest.
Introduction to Bugs – Life Cycle 7
❖ And, like any bugs in your garden, these bugs also have a life cycle:
❑ Retest: At this stage the tester do the retesting of the changed
code which developer has given to him to check whether the
defect got fixed or not.
❑ Verified: The tester tests the bug again after it got fixed by the
developer. If thebug is not present in the software, he approves
that the bug is fixed and changes the status to “verified”.
❑ Reopen: If the bug still exists even after the bug is fixed by the
developer, the tester changes the status to “reopened”. The bug
goes through the life cycle once again.
❑ Closed: Once the bug is fixed, it is tested by the tester. If the
tester feels that the bug no longer exists in the software, he
changes the status of the bug to “closed”. This state means that
the bug is fixed, tested and approved.
Introduction to Bugs – Life Cycle 8
❖ And, like any bugs in your garden, these bugs also have a life cycle:
❑ Duplicate: If the bug is repeated twice or the two bugs mention
the same concept of the bug, then one bug status is changed to
“duplicate“.
❑ Rejected: If the developer feels that the bug is not genuine, he
rejects the bug. Then the state of the bug is changed to
“rejected”.
❑ Deferred: The bug, changed to deferred state means the bug is
expected to be fixed in next releases. The reasons for changing
the bug to this state have many factors. Some of them are
priority of the bug may be low, lack of time for the release or the
bug may not have major effect on the software.
❑ Not a bug: The state given as “Not a bug” if there is no change
in the functionality of the application. For an example: If
customer asks for some change in the look and field of the
application like change of color of some text then it is not a bug
but just some change in the looks of the application.
Introduction to Bugs – Life Cycle 9
❖ To be more specific, here is how this works…
Introduction to Bugs - Categories 10
❖ Now that we've explored the life cycle of a bug, it's important to understand the broader
context of software errors. Bugs are just one type of problem that can occur during
development. To manage and resolve these issues effectively, we need to categorize
them properly. In Java, programming errors can be categorized into three types: syntax
errors, runtime errors, and logic errors.
11
❖ Introduction to Bugs
❖ Syntax Errors
❖ Runtime Errors
❖ Logic Errors
❖ Exceptions Handling
❖ Debugging Strategies
❖ Final Touches
Syntax Errors 12
❖ Errors that are detected by the compiler are called syntax errors or compile errors.
Syntax errors result from errors in code construction, such as mistyping a keyword,
omitting some necessary punctuation, or using an opening brace without a
corresponding closing brace. These errors are usually easy to detect because the
compiler tells you where they are and what caused them. For example:

1 public class ShowSyntaxErrors {


2 public static main(String[] args) {
3 System.out.println("Welcome to Java);
4 }
5 } Can you show me the errors?
Syntax Errors 13
❖ For example:

1 public class ShowSyntaxErrors {


2 public static main(String[] args) {
3 System.out.println("Welcome to Java);
4 }
5 }

Two errors are reported:


❑ The keyword void is missing before main in line 2.
❑ The string Welcome to Java should be closed with
a closing quotation mark in line 3.
Syntax Errors 14
❖ Since a single error will often display many lines of compile errors, it is a good practice
to fix errors from the top line and work downward. Fixing errors that occur earlier in the
program may also fix additional errors that occur later.

Tip: If you don’t know how to correct it, compare


your program closely, character by character, with
similar examples in the text. In the first few weeks
of this course, you will probably spend a lot of time
fixing syntax errors. Soon you will be familiar with
Java syntax and can quickly fix syntax errors.
15
❖ Introduction to Bugs
❖ Syntax Errors
❖ Runtime Errors
❖ Logic Errors
❖ Exceptions Handling
❖ Debugging Strategies
❖ Final Touches
Run-time Errors 16
❖ Runtime errors are errors that cause a program to terminate abnormally. They occur
while a program is running if the environment detects an operation that is impossible to
carry out. Input mistakes typically cause runtime errors. An input error occurs when the
program is waiting for the user to enter a value, but the user enters a value that the
program cannot handle. For instance, if the program expects to read in a number, but
instead the user enters a string, this causes data-type errors to occur in the program.
❖ Another example of runtime errors is division by zero. This happens when the divisor is
zero for integer divisions. For instance:
1 public class ShowRuntimeErrors {
2 public static void main(String[] args) {
3 System.out.println(1 / 0);
4 }
5 }
17
❖ Introduction to Bugs
❖ Syntax Errors
❖ Runtime Errors
❖ Logic Errors
❖ Exceptions Handling
❖ Debugging Strategies
❖ Final Touches
Logic Errors 18
❖ Logic errors occur when a program does not perform the way it was intended to. Errors
of this kind occur for many different reasons. For example, suppose you wrote the
program to convert Celsius 35 degrees to a Fahrenheit degree.

Notice
❑ You will get Fahrenheit 67 degrees, which is wrong. It should be 95.0. In Java, the division for integers is
the quotient - the fractional part is truncated - so in Java 9 / 5 is 1. To get the correct result, you need to
use 9.0 / 5, which results in 1.8.
That’s all three types of errors, but…

How can we handle them?

19
20
❖ Introduction to Bugs
❖ Syntax Errors
❖ Runtime Errors
❖ Logic Errors
❖ Exceptions Handling
❖ Debugging Strategies
❖ Final Touches
Exceptions Handling 21
❖ An exception is an object that’s created when an error occurs in a Java program and
Java can’t automatically fix it. The exception object contains information about the type
of error that occurred. However, the most important information - the cause of the error
- is indicated by the name of the exception class used to create the exception. You don’t
usually have to do anything with an exception object other than figure out which one
you have. Each type of exception that can occur is represented by a different exception
class.
❖ For example, here are some typical exceptions:
❑ IllegalArgumentException: You passed an incorrect argument to a method.
❑ InputMismatchException: The console input doesn’t match the data type expected by a method of
the Scanner class.
❑ ArithmeticException: You tried an illegal type of arithmetic operation, such as dividing an integer
by zero.
❑ IOException: A method that performs I/O encountered an unrecoverable I/O error.
❑ ClassNotFoundException: A necessary class couldn’t be found.
Exceptions Handling 22
❖ There are many other types of exceptions besides these. And, you might need to know a
few other things about exceptions (some were explained in lecture 06):
❑ When an error occurs and an exception object is created, Java is said to have thrown an
exception. Java has a pretty good throwing arm, so the exception is always thrown right
back to the statement that caused it to be created.
❑ The statement that caused the exception can catch the exception if it wants it. But it doesn’t
have to catch the exception if it doesn’t want it. Instead, it can duck and let someone else
catch the exception. That someone else is the statement that called the method that’s
currently executing.
❑ If everyone ducks and the exception is never caught by the program, the program ends
abruptly and displays a nasty looking exception message on the console.
❑ Two basic types of exceptions in Java are checked exceptions and unchecked exceptions:
➢ A checked exception is an exception that the compiler requires you to provide for it one
way or another. If you don’t, your program doesn’t compile.
➢ An unchecked exception is an exception that you can provide for, but you don’t have to.
Exceptions Handling 23
❖ As mentioned earlier, whenever you use a statement that might throw an exception, you should
write special code to anticipate and catch the exception. That way, your program won’t crash if
the exception occurs. You catch an exception by using a try-catch block:

try
{
// statements that can throw exceptions
}
catch (exception-type identifier)
{
// statements executed when exception is thrown
}
Exceptions Handling 24
❖ Here is a simple example:

public class DivideByZero {


public static void main(String[] args) {
int a = 5;
int b = 0; // you know this won’t work
try {
int c = a / b; // but you try it anyway
} catch (ArithmeticException e) {
System.out.println("Oops, you can’t divide by zero.");
}
}
}
25

In the previous lecture, we covered how to catch and handle specific


exceptions in Java. However, in real-world applications, you may
encounter multiple types of exceptions, and it might not be practical to
write separate handling logic for each one. So, what should you do
when dealing with numerous exceptions or unanticipated ones?
Exceptions Handling 26
❖ If you have some code that might throw several different types of exceptions, and you
want to provide specific processing for some but general processing for all the others,
try this:
try {
// statements that might throw several types of exceptions
} catch (InputMismatchException e) {
// statements that process InputMismatchException
} catch (IOException e) {
// statements that process IOException
} catch (AnyException e) {
// statements that process any other exceptions
} catch (Exception e) {
// statements that process all other exception types
}
Notice
❑ When you code more than one catch block on a try statement, always list the more specific
exceptions first. If you include a catch block to catch Exception, list it last.
Exceptions Handling 27
❖ If you prefer not to handle a specific exception in a catch block, you can use the more
general Exception class. In Java, Exception serves as a catch-all for various exceptions,
since all other exception types are subclasses of it. For example:

try {
int c = 5 / 0;
} catch (Exception e) {
System.err.println("Exceptions: / by zero.");
}
Exceptions Handling 28
❖ As you can see, in most cases, the catch block of a try statement won’t do anything at all
with the exception object passed to it. However, you may occasionally want to display
an error message; exception objects have a few interesting methods that can come in
handy from time to time:

Example
try {
int c = a / b;
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
Exceptions Handling 29
❖ Now that we've explored how try-catch blocks allow us to handle exceptions, it’s also
important to ensure that certain actions always occur, whether an exception is thrown or
not. In Java, the finally block guarantees that, regardless of what happens inside the try
or catch blocks, critical cleanup operations will always be executed. This is particularly
useful when dealing with tasks like closing files, releasing resources, or closing database
connections.
try {
// statements that can throw exceptions
} catch (Exception-type identifier) {
// statements executed when exception is thrown
} finally {
// statements that are executed whether or not
exceptions occur
}
30

Uhm… Now that we understand


the basics of exception handling in
Java, let's dive deeper into
exceptions.
Exceptions Handling 31
❖ The previous section introduced only a handful of exception classes. However, the Java
API offers a wide range of predefined exception classes to handle various error
scenarios. Below are some common predefined exception types that developers can use
in their applications:
Exceptions Handling 32
❖ The Throwable class is the root of exception classes. All Java exception classes inherit
directly or indirectly from Throwable. Note that you can also create your own exception
classes by extending Exception or a subclass of Exception.
❖ The exception classes can be classified into three major types:
❑ System errors are thrown by the JVM and are represented in the Error class. The Error class
describes internal system errors, though such errors rarely occur. If one does, there is little you
can do beyond notifying the user and trying to terminate the program gracefully. For instance:
LinkageError, VirtualMachineError.
❑ Exceptions are represented in the Exception class, which describes errors caused by your
program and by external circumstances. These errors can be caught and handled by your
program. For example: ClassNotFoundException, IOException, etc.
❑ Runtime exceptions are represented in the RuntimeException class, which describes
programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
Runtime exceptions are generally thrown by the JVM. For example: ArithmeticException,
NullPointerException, etc.
Exceptions Handling 33
❖ RuntimeException, Error, and their subclasses are known as unchecked exceptions. All
other exceptions are known as checked exceptions, meaning that the compiler forces the
programmer to check and deal with them in a try-catch block or declare it in the method
header.
❖ In most cases, unchecked exceptions reflect programming logic errors that are
unrecoverable. For example, a NullPointerException is thrown if you access an object
through a reference variable before an object is assigned to it; an
IndexOutOfBoundsException is thrown if you access an element in an array outside the
bounds of the array. These are logic errors that should be corrected in the program.
Unchecked exceptions can occur anywhere in a program. To avoid cumbersome overuse
of try-catch blocks, Java does not mandate that you write code to catch or declare
unchecked exceptions.
Exceptions Handling – Checked Exceptions 34
❖ Checked exceptions are exceptions that the designers of Java feel your programs
absolutely must provide for, one way or another. Whenever you code a statement that
might throw a checked exception, your program must do one of two things:
❑ Catch the exception by placing the statement within a try statement that has a catch
block for the exception.
❑ Specify a throws clause on the method that contains the statement to indicate that
your method doesn’t want to handle the exception, so it’s passing the exception up
the line.
Exceptions Handling – Checked Exceptions 35
❖ For example:

/**
* Converts a hex string into a decimal number and throws a
* NumberFormatException if the string is not a hex string
*/
public static int hexToDecimal(String hex) throws NumberFormatException {
int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
if (!(hex.charAt(i) >= '0' && hex.charAt(i) <= '9') ||
!(hex.charAt(i) >= 'A' && hex.charAt(i) <= 'F'))
throw new NumberFormatException("String is not a hex string");
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
}

return decimalValue;
}
Exceptions Handling – Custom Exceptions 36
❖ You know, Java provides quite a few exception classes. Use them whenever possible
instead of defining your own exception classes. However, if you run into a problem that
cannot be adequately described by the predefined exception classes, you can create your
own exception class, derived from Exception or from a subclass of Exception, such as
IOException. For example:
//Custom Exception
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}

public class CustomExceptionDemo {


// A function that throws a custom exception
public static void checkNumber(int number) throws MyCustomException {
if (number < 0) {
throw new MyCustomException("Number is negative!");
}
System.out.println("Number is positive or zero: " + number);
}
}
37

Don't worry if this isn't entirely clear yet. You'll understand


the specifics when we dive into it further in PR2. For now,
just remember that to create a custom exception, you
simply need to define a class that extends the Exception
class, as demonstrated in the earlier example.
That’s almost everything about Exceptions,
Do you have any question?

38
39

Okay, so exceptions help catch Exactly! Logic errors are a bit sneaky because your
errors like runtime and code runs without any compile or runtime errors,
compile-time ones. But what but it doesn't behave as expected. The program
about logic errors? They seem might give the wrong results or behave
tricky because they don't cause unexpectedly. To catch these, you'll need to rely on
exceptions, right? debugging strategies, testing, or careful inspection
of your code's flow. Let’s see what can we do…
40
❖ Introduction to Bugs
❖ Syntax Errors
❖ Runtime Errors
❖ Logic Errors
❖ Exceptions Handling
❖ Debugging Strategies
❖ Final Touches
Debugging Strategies 41
❖ As mentioned, syntax errors are easy to find and easy to correct because the compiler
gives indications as to where the errors came from and why they are there. Runtime
errors are not difficult to find either, because the Java interpreter displays them on the
console when the program aborts. Finding logic errors, on the other hand, can be very
challenging.
❖ Logic errors are called bugs. The process of finding and correcting errors is called
debugging. A common approach to debugging is to use a combination of methods to
help pinpoint the part of the program where the bug is located. You can hand-trace the
program (i.e., catch errors by reading the program), or you can insert print statements in
order to show the values of the variables or the execution flow of the program. These
approaches might work for debugging a short, simple program, but for a large, complex
program, the most effective approach is to use a debugger utility.
Debugging Strategies 42
❖JDK includes a command-line debugger, jdb, which is invoked with a class name. jdb is
itself a Java program, running its own copy of Java interpreter. All the Java IDE tools,
such as Eclipse and NetBeans, include integrated debuggers. The debugger utilities let
you follow the execution of a program. They vary from one system to another, but they
all support most of the following helpful features.
❑ Executing a single statement at a time: The debugger allows you to execute one statement at a time
so that you can see the effect of each statement.
❑ Tracing into or stepping over a method: If a method is being executed, you can ask the debugger to
enter the method and execute one statement at a time in the method, or you can ask it to step over the
entire method. You should step over the entire method if you know that the method works. For
example, always step over system-supplied methods, such as System.out.println.
❑ Setting breakpoints: You can also set a breakpoint at a specific statement. Your program pauses when
it reaches a breakpoint. You can set as many breakpoints as you want. Breakpoints are particularly
useful when you know where your programming error starts. You can set a breakpoint at that
statement and have the program execute until it reaches the breakpoint.
Debugging Strategies 43
❖JDK includes a command-line debugger, jdb, which is invoked with a class name. jdb is
itself a Java program, running its own copy of Java interpreter. All the Java IDE tools,
such as Eclipse and NetBeans, include integrated debuggers. The debugger utilities let
you follow the execution of a program. They vary from one system to another, but they
all support most of the following helpful features.
❑ Displaying variables: The debugger lets you select several variables and display their values. As you
trace through a program, the content of a variable is continuously updated.
❑ Displaying call stacks: The debugger lets you trace all of the method calls. This feature is helpful
when you need to see a large picture of the program-execution flow.
❑ Modifying variables: Some debuggers enable you to modify the value of a variable when debugging.
This is convenient when you want to test a program with different samples but do not want to leave
the debugger.
Now that you have learned
Exceptions and Debugging.
Do you have any question?
If you don’t, in the next
section, I will show the
summary of this lecture...
Summary 45
1. Exception handling enables a method to throw an exception to its caller.
2. A Java exception is an instance of a class derived from java.lang.Throwable. Java
provides a number of predefined exception classes, such as Error, Exception,
RuntimeException, ClassNotFoundException, NullPointerException, and
ArithmeticException. You can also define your own exception class by
extending Exception.
3. Exceptions occur during the execution of a method. RuntimeException and
Error are unchecked exceptions; all other exceptions are checked.
4. When declaring a method, you have to declare a checked exception if the method
might throw it, thus telling the compiler what can go wrong.
5. The keyword for declaring an exception is throws, and the keyword for throwing
an exception is throw.
6. To invoke the method that declares checked exceptions, enclose it in a try
statement. When an exception occurs during the execution of the method, the
catch block catches and handles the exception.
Summary 46
7. If an exception is not caught in the current method, it is passed to its caller. The
process is repeated until the exception is caught or passed to the main method.
8. Various exception classes can be derived from a common superclass. If a catch
block catches the exception objects of a superclass, it can also catch all the
exception objects of the subclasses of that superclass.
9. The order in which exceptions are specified in a catch block is important. A
compile error will result if you specify an exception object of a class after an
exception object of the superclass of that class.
10. When an exception occurs in a method, the method exits immediately if it does
not catch the exception. If the method is required to perform some task before
exiting, you can catch the exception in the method and then rethrow it to its caller.
This brings us to the
end of this lecture!
It’s time for Final
Touches…

47
Final Touches 48
❖Introduction to Bugs
❑ “First actual case of bug being found.”
❑ The story goes that on September 9th, 1947, computer scientist Grace Hopper found a moth in the Harvard Mark
II computer’s log book and reported the world’s first literal computer bug. However, the term “bug”, in the sense
of technical error, dates back at least to 1878 and with Thomas Edison.
❑ On your programming journey, you are destined to encounter innumerable red errors. Some even say that
debugging is over 75% of the development time. But what makes a programmer successful isn’t avoiding errors;
it’s knowing how to find the solution.
❑ In Java, there are many different ways of classifying errors, but they can be boiled down to three categories:
1. Syntax errors: Errors found by the compiler.
2. Run-time errors: Errors that occur when the program is running.
3. Logic errors: Errors found by the programmer looking for the causes of erroneous results.
❑ Generally speaking, the errors become more difficult to find and fix as you move down the above list.

❑ In this section, we will be looking at different errors and different error messages, and we’ll teach you how to
think about errors in your code a little differently.
Final Touches 49
❖Syntax Errors
❑ When we are writing Java programs, the compiler is our first line of defense against errors. It can catch syntax
errors.
❑ Syntax errors represent grammar errors in the use of the programming language. They are the easiest to find and
correct. The compiler will tell you where it got into trouble, and its best guess as to what you did wrong.
❑ Some common syntax errors are:
1. Misspelled variable and method names
2. Omitting semicolons ;
3. Omitting closing parenthesis ), square bracket ], or curly brace }
❑ Here’s an example of a syntax error message:
Debug.java:5: error: ';' expected
int year = 2019
^

❑ Usually, the error is on the exact line indicated by the compiler, or the line just before it; however, if the problem
is incorrectly nested braces, the actual error may be at the beginning of the nested block.
Final Touches 50
❖Run-time Errors
❑ If our program has no compile-time errors, it’ll run. This is where the fun really starts.
❑ Errors which happen during program execution (run-time) after successful compilation are called run-time errors.
Run-time errors occur when a program with no compile-time errors asks the computer to do something that the
computer is unable to reliably do.

❑ Some common run-time errors:


1. Division by zero also known as division error
2. Trying to open a file that doesn’t exist
❑ There is no way for the compiler to know about these kinds of errors when the program is compiled.

❑ Here’s an example of a run-time error message:


Debug.java:5: error: ';' expected
int year = 2019
^
Final Touches 51
❖Exceptions
❑ In the previous lecture when we were dealing with run-time errors, you might’ve noticed a new word in the error
message: “Exception”.
❑ Java uses exceptions to handle errors and other exceptional events. Exceptions are the conditions that occur at
runtime and may cause the termination of the program.
❑ When an exception occurs, Java displays a message that includes the name of the exception, the line of the
program where the exception occurred, and a stack trace. The stack trace includes:
1. The method that was running
2. The method that invoked it
3. The method that invoked that one
4. and so on…
❑ Make sure to examine it.
❑ Some common exceptions that you will see in the wild:
➢ ArithmeticException: Something went wrong during an arithmetic operation; for example, division by zero.
➢ NullPointerException: You tried to access an instance variable or invoke a method on an object that is currently
null.
➢ ArrayIndexOutOfBoundsException: The index you are using is either negative or greater than the last index of
the array (i.e., array.length-1).
➢ FileNotFoundException: Java didn’t find the file it was looking for.
Final Touches 52
❖Exception Handling
❑ Exception handling is an essential feature of Java programming that allows us to use run-time error exceptions to
make our debugging process a little easier.
❑ One way to handle exceptions is using the try/catch:
➢ The try statement allows you to define a block of code to be tested for errors while it is being executed.
➢ The catch statement allows you to define a block of code to be executed if an error occurs in the try block.
❑ The try and catch keywords come in pairs, though you can also catch several types of exceptions in a single
block:
Final Touches 53
❖Exception Handling
❑ Notice how we used System.err.println() here instead of System.out.println(). System.err.println() will print
to the standard error and the text will be in red.
❑ You can also chain exceptions together:
Final Touches 54
❖Logic Errors
❑ Once we have removed the syntax errors and run-time errors, the program runs successfully. But sometimes, the
program still doesn’t do what we want it to do or no output is produced. Hmmm…
❑ These types of errors, which provide incorrect output, but appear to be error-free, are called logic errors. Logic
errors occur when there is a design flaw in your program. These are some of the most common errors that happen
to beginners and also usually the most difficult to find and eliminate.
❑ Because logical errors solely depend on the logical thinking of the programmer, your job now is to figure out
why the program didn’t do what you wanted it to do.
❑ Some common logic errors:
➢ Program logic is flawed
➢ Some “silly” mistake in an if statement or a for/while loop
❑ Note: Logic errors don’t have error messages. Sometimes, programmers use a process called test-driven
development (TDD), a way to give logic errors error messages and save yourself a lot of headaches!
Final Touches 55
❖Debugging Techniques
❑ If you have examined the code thoroughly, and you are sure the compiler is compiling the right source file, it is
time for desperate measures:
❑ 1. Divide and conquer: Comment out or temporarily delete half the code to isolate an issue.
➢ If the program compiles now, you know the error is in the code you deleted. Bring back about half of what
you removed and repeat.
➢ If the program still doesn’t compile, the error must be in the code that remains. Delete about half of the
remaining code and repeat.
Tip: In most code editors, one can highlight a block of code and use the keyboard shortcut command + / to
comment it out.
❑ 2. Print statements for the rescue: Use System.out.println() to check variable/return values at various points
throughout the program.
A lot of the time with logic errors, there was a flawed piece of logic, a miscalculation, a missing step, etc. By
printing out the values at different stages of the execution flow, you can then hopefully pinpoint where you
made a mistake.
Final Touches 56
❖Debugging Techniques
❑ For example, there is a logical error: it is not calculating the areas right for one of the shapes. Find the bug!

public static double getTriangleArea(int base, int height) {


System.out.println();
double area = (base * height) * 2.0;
System.out.println("The area is " + area + ".");
return area;
}

public static double getRectangleArea(int length, int width) {


System.out.println();
double area = length * width * 1.0;
System.out.println("The area is " + area + ".");
return area;
}

public static double getCircleArea(int radius) {


System.out.println();
double area = Math.PI * radius * radius;
System.out.println("The area is " + area + ".");
return area;
}
Final Touches 57
❖Review
❑ Finding bugs is a huge part of a programmer’s life. Don’t be intimidated by them… embrace them. Errors in your
code mean you’re trying to do something cool!
❑ In this lesson, we have learned about the three types of Java errors:
➢ Syntax errors: Errors found by the compiler.
➢ Run-time errors: Errors found by checks in a running program.
➢ Logic errors: Errors found by the programmer looking for the causes of erroneous results.
❑ Remember, Google and Stack Overflow are a programmer’s best friends. For some more motivation, check out
this blog post: Thinking About Errors in Your Code Differently.
❑ Sometimes once you’ve tracked down a bug, you might still be confused on how to fix it! Whenever you want to
know more about how Java works and what it can do, the best place to go is documentation. You can find the
Java documentation at Oracle.
Final Touches 58
❖Chained Exceptions
❑ The catch block rethrows the original exception. Sometimes, you may need to throw a new exception
(with additional information) along with the original exception. This is called chained exceptions.
Final Touches 59
❖Advanced Techniques
❑ Debuggers have many advanced techniques. Three common ones are:
➢ Conditional breakpoint - Normally, the debugger stops where you asked for a breakpoint. If you
are in a loop or have a clue what values trigger the problem, you don't want that. A conditional
breakpoint allows you to add a bit of Java code to your breakpoint so it will only stop when that
condition is true. This approach avoids having to hit resume a lot of times until you get to the
value you care about.
➢ Evaluation - Once you get to your breakpoint, you can write Java code to determine the state of
affairs. For example, you can call methods on the available variables.
➢ Changing data - You can manually change the value of a variable in the debugger and let the
code continue to run. It will use your new, updated value instead of the original one. This lets you
explore the impact of a potential fix.
Fun fact: If you use Eclipse, you can have a look at this guideline: https://www.eclipse.org/community/eclipse_newsletter/2017/june/article1.php
If you use IntelliJ, you can have a look at this guideline: https://www.jetbrains.com/help/idea/debugging-your-first-java-application.html
If you use NetBeans, you can have a look at this guideline: https://netbeans.apache.org/tutorial/main/kb/docs/java/debug-visual/
60

Thanks!
Any questions?
For an in-depth understanding of Java, I highly recommend
referring to the textbooks. This slide provides a brief overview
and may not cover all the details you're eager to explore!

You might also like