Chapter 6
Handling Exceptions and Debugging
Overview
• Recognizing error types
• Exceptions
• Debugging Your Applications
• Testing Your Applications
2
Recognizing Error Types
• Identifying syntax errors
• Identifying runtime errors
• Identifying logical errors
3
Identifying Syntax Errors
• Misspelled class, variable, or method names
• Misspelled keywords
• Missing semicolons
• Missing return type for methods
• Out of place or mismatched parentheses and brackets
• Undeclared or uninitialized variables
• Incorrect format of loops, methods, or other structures
4
Identifying Syntax Errors
public class errors {
public static vod main(String[] args) {
age = 30;
int retirementFund = 10000;
int yearsInRetirement = 0;
String name = "David Johnson",
for (int i = age; <= 65; ++){
recalculate(retirementFund,0.1);
}
int monthlyPension = retirementFund/yearsInRetirement/12
System.out.printline(name + " will have $" + monthlyPension
+ " per month for retirement."];
}
public static recalculate(fundAmount, rate){
fundAmount = fundAmount*(1+rate);
}}}
5
Identifying Syntax Errors
public class Errors {
public static void main(String[] args) {
int age = 30;
int retirementFund = 10000;
int yearsInRetirement = 0;
String name = "David Johnson“;
for (int i = age; i <= 65; i++){
recalculate(retirementFund,0.1);
}
int monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.“);
}
public static void recalculate(double fundAmount, double rate){
fundAmount = fundAmount*(1+rate);
}
}
6
Identifying Runtime Errors
Line 13: int monthlyPension = retirementFund/yearsInRetirement/12;
Remember: int yearsInRetirement = 0;
7
Identifying Logical Errors
public class Errors {
public static void main(String[] args) {
int age = 30;
int retirementFund = 10000;
int yearsInRetirement = 20;
String name = "David Johnson“;
for (int i = age; i <= 65; i++){
recalculate(retirementFund,0.1);
}
int monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.“);
}
public static void recalculate(double fundAmount, double rate){
fundAmount = fundAmount*(1+rate);
}}
Output:
David Johnson will have $41 per month for retirement.
8
Identifying Logical Errors
public class errors {
public static void main(String[] args) {
int age = 30;
double retirementFund = 10000;
int yearsInRetirement = 20;
String name = "David Johnson“;
for (int i = age; i <= 65; i++){
retirementFund = recalculate(retirementFund,0.1);
}
double monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.“);
}
public static double recalculate(double fundAmount, double rate){
return fundAmount*(1+rate);
}} Output:
David Johnson will have $1288.0283555362819 per month for retirement.
9
BigDecimal
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html
Immutable, arbitrary-precision signed decimal numbers.
Be very careful with the BigDecimal examples in the book!
10
Identifying Logical Errors
import java.math.BigDecimal;
public class Errors {
public static void main(String[] args) {
int age = 30;
BigDecimal retirementFund = new BigDecimal("10000.00");
// set the scale to 2 decimal points
// and the rounding to round up when the next digit is >= 5
retirementFund.setScale(2,BigDecimal.ROUND_HALF_UP);
BigDecimal yearsInRetirement = new BigDecimal("20.00"); Error-prone use of method and deprecated!
String name = "David Johnson";
for (int i = age; i <= 65; i++){ public static BigDecimal recalculate(BigDecimal
retirementFund = recalculate(retirementFund,new fundAmount, BigDecimal rate){
BigDecimal("0.10")); // use BigDecimal methods for arithmetic
} // operations
return fundAmount.multiply(rate.add(new
BigDecimal monthlyPension =
retirementFund.divide(yearsInRetirement.multiply(new BigDecimal("1.00")));
BigDecimal("12.00")),2, BigDecimal.ROUND_HALF_UP); }
System.out.println(name + " will have $" + monthlyPension+ " per
}
month for retirement.");
} Output:
… David Johnson will have $1288.03 per month
for retirement.
11
Identifying Logical Errors
import java.math.BigDecimal; System.out.println(name + " will have $" +
import java.math.RoundingMode; monthlyPension+ " per month for retirement.");
public class Errors { }
…
public static void main(String[] args) {
int age = 30;
public static BigDecimal recalculate(BigDecimal
BigDecimal retirementFund = new BigDecimal("10000.00"); fundAmount, BigDecimal rate){
// use BigDecimal methods for arithmetic
// set the scale to 2 decimal points // operations
// and the rounding to round up when the next digit is >= 5 return fundAmount.multiply(rate.add(new
retirementFund = retirementFund.setScale(2, BigDecimal("1.00")));
RoundingMode.HALF_UP); }
}
BigDecimal yearsInRetirement = new BigDecimal("20.00");
String name = "David Johnson";
for (int i = age; i <= 65; i++){
retirementFund = recalculate(retirementFund,new
BigDecimal("0.10"));
}
BigDecimal monthlyPension = Output:
retirementFund.divide(yearsInRetirement.multiply(new David Johnson will have $1288.03 per month
BigDecimal("12.00")),2, RoundingMode.HALF_UP); for retirement.
12
Exceptions
• Events that disrupt the execution of a program
• Common exceptions
– NullPointerException: accessing an object that doesn’t exist/has
not been intialized
– IndexOutOfBoundsException: try to access an element outside
the limits of an indexed object (e.g. array)
– StackOverFlowError: too many parameters and/or local
variables created due to e.g. recursion
– OutOfMemoryError: too many objects created due to e.g.
infinite loop
13
Exceptions
public class ExceptionExamples {
public static void main(String[] args) {
Person employee;
printPerson(employee);
}
public static void printPerson(Person myPerson){
System.out.println(myPerson.name + " is " + myPerson.age + " years old.");
}
}
class Person{
String name;
int age;
}
14
Exceptions
public class ExceptionExamples {
public static void main(String[] args) {
Person employee;
printPerson(employee);
}
public static void printPerson(Person myPerson){
System.out.println(myPerson.name + " is " + myPerson.age + " years old.");
}
}
class Person{
String name;
int age;
} Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable employee may not have been initialized.
15
Exceptions
public class ExceptionExamples {
public static void main(String[] args) {
Person employee= new Person();
printPerson(employee);
}
public static void printPerson(Person myPerson){
System.out.println(myPerson.name + " is " + myPerson.age + " years old.");
}
}
class Person{
String name;
int age;
} Output:
null is 0 years old.
16
Exceptions
public class ExceptionExamples { class Person{
public static void main(String[] args) String name;
{ int age;
Person employee = new Person(); JobType job;
printPerson(employee); Person (){
} }
public static void printPerson(Person }
myPerson){ class JobType{
System.out.println(myPerson.name + " String jobName;
is " + myPerson.age + " years old and int salaryBand;
works as a " + myPerson.job.jobName);
JobType (){
}
}
}
}
…
17
Exceptions
public class ExceptionExamples { class Person{
public static void main(String[] args) String name;
{ int age;
Person employee = new Person(); JobType job;
printPerson(employee); Person (){
} }
public static void printPerson(Person }
myPerson){ class JobType{
System.out.println(myPerson.name + " String JobName;
is " + myPerson.age + " years old and int salaryBand;
works as a " + myPerson.job.JobName);
JobType (){
}
}
}
}
…
Output:
Exception in thread "main" java.lang.NullPointerException 18
Exceptions
public class ExceptionExamples { class Person{
String name;
int age;
public static void main(String[] args) {
JobType job;
JobType manager = new JobType("Manager", 6);
Person employee = new Person("Bob Little", 47,
Person (String name, int age, JobType job){
manager);
this.name = name;
printPerson(employee);
this.age = age;
}
this.job = job;
}
public static void printPerson(Person myPerson){ }
System.out.println(myPerson.name + " is " + class JobType{
myPerson.age + String JobName;
" years old and works as a " + int salaryBand;
myPerson.job.JobName);
} JobType (String name, int band){
} JobName = name;
… salaryBand = band;
Output: }}
Bob Little is 47 years old and works as a Manager
19
Exceptions
public class IndexExceptionExample {
public static void main(String[] args) {
int[] hoursWorked = {7,8,7,9,5};
int totalHours = 0;
for (int i = 0; i <= hoursWorked.length; i++){
totalHours += hoursWorked[i];
}
System.out.println("Total Hours = " + totalHours);
}
20
Exceptions
public class IndexExceptionExample {
public static void main(String[] args) {
int[] hoursWorked = {7,8,7,9,5};
int totalHours = 0;
for (int i = 0; i <= hoursWorked.length; i++){
totalHours += hoursWorked[i];
}
System.out.println("Total Hours = " + totalHours);
}
} Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
21
Exceptions
public class IndexExceptionExample {
public static void main(String[] args) {
int[] hoursWorked = {7,8,7,9,5};
int totalHours = 0;
for (int i = 0; i < hoursWorked.length; i++){
totalHours += hoursWorked[i];
}
System.out.println("Total Hours = " + totalHours);
}
}
22
Exceptions
import java.util.ArrayList;
public class EndlessLoop {
static ArrayList<String> myStrings = new ArrayList<String>();
public static void main(String[] args) {
for (int i = 0; i >= 0; i++) {
myStrings.add("String number: " + i);
}
}
}
23
Exceptions
import java.util.ArrayList;
public class EndlessLoop {
static ArrayList<String> myStrings = new ArrayList<String>();
public static void main(String[] args) {
for (int i = 0; i >= 0; i++) {
myStrings.add("String number: " + i);
}
}
Output:
} Exception in thread "main“ java.lang.OutOfMemoryError
24
Exceptions
public class EndlessMethodCall {
public static void main(String[] args) {
printMe();
}
public static void displayMe(){
printMe();
}
public static void printMe(){
displayMe();
}
}
25
Exceptions
public class EndlessMethodCall {
public static void main(String[] args) {
printMe();
}
public static void displayMe(){
printMe();
}
public static void printMe(){
displayMe();
}
} Output:
Exception in thread "main" java.lang.StackOverflowError
26
Catching Exceptions
• try/catch block
• Syntax:
try {
// execute some statements
} catch (Exception exc){
// statements to handle the exception
} finally {
// no matter what, do this
}
27
Catching Exceptions
public class Error {
public static void main(String[] args) {
int numerator=10;
int denominator=0;
try{
int ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae) {
System.out.println("Denominator should not be 0!");
}
}
}
Output:
Denominator should not be 0!
28
Catching Exceptions
public class Error {
public static void main(String[] args) {
double numerator=10;
double denominator=0;
try{
double ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae){
System.out.println("Denominator should not be 0.");}
}}
Output:
Infinity 29
Catching Exceptions
public class Error {
public static void main(String[] args) {
double numerator=10;
double denominator=0;
try{
if (denominator == 0) {throw new ArithmeticException();};
double ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae){
System.out.println("Denominator should not be 0!");}
}
} Output:
Denominator should not be 0!
30
Catching Exceptions
public class Error {
public static void main(String[] args) {
double numerator=10;
double denominator=2;
try{
if (denominator == 0) {throw new ArithmeticException();};
double ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae){
System.out.println("Denominator should not be 0.");}
finally{
System.out.println("Finally was reached!");} Output:
}} 5.0
Finally was reached!
31
Catching Exceptions
public class Error {
public static void main(String[] args) {
double numerator=10;
double denominator=0;
try{
if (denominator == 0) {throw new ArithmeticException();};
double ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae){
System.out.println("Denominator should not be 0.");}
finally{
System.out.println("Finally was reached!");}
}} Output:
Denominator should not be 0.
Finally was reached!
32
Catching exceptions
import java.text.DecimalFormat; System.out.println("Please provide correct
import java.util.InputMismatchException; input!");
import java.util.Scanner; } finally {
public class Error { scan.close();
static Scanner scan = new Scanner(System.in); }}}
public static void main(String[] args) {
try {
System.out.print("Enter the loan amount: ");
double principle = scan.nextDouble();
System.out.print("Enter the interest rate: ");
double rate = scan.nextDouble(); Input:
System.out.print("Enter the loan term (in years): "); Enter the loan amount: Bart
double years = scan.nextInt(); Output:
double interest = principle*rate*years;
double total = principle + interest;
Please provide correct input!
double payment = total/years/12;
DecimalFormat df = new DecimalFormat ("0.##");
System.out.println("Monthly payment: $“ + df.format(payment));
} catch (InputMismatchException exc){
…
33
Catching exceptions
import java.text.DecimalFormat;
import java.util.Scanner;
public class Error {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)){
System.out.print("Enter the loan amount: ");
double principle = scan.nextDouble();
System.out.print("Enter the interest rate: ");
double rate = scan.nextDouble();
System.out.print("Enter the loan term (in years): ");
double years = scan.nextInt();
double interest = principle*rate*years;
double total = principle + interest;
double payment = total/years/12;
DecimalFormat df = new DecimalFormat ("0.##");
System.out.println("Monthly payment: $" + df.format(payment));
} catch (Exception exc){
System.out.println(exc);
}}}
34
Catching exceptions
import java.text.DecimalFormat; public static double[] scanValues() throws
import java.util.InputMismatchException; InputMismatchException {
import java.util.Scanner; double[] values = new double[3];
Scanner scan = new Scanner(System.in);
public class Error {
try {
public static void main(String[] args) {
System.out.print("Enter loan amount: ");
try {
values[0] = scan.nextDouble();
double[] userValues = scanValues();
double payment = System.out.print("Enter interest rate: ");
(userValues[0]+userValues[0]*userValues[1]*userValues[2])/userV values[1] = scan.nextDouble();
alues[2]/12; System.out.print("Enter loan term: ");
DecimalFormat df = new DecimalFormat("0.##"); values[2] = scan.nextInt();
System.out.println("Monthly payment: $" + df.format(payment)); } finally {
} catch (InputMismatchException ime) {
scan.close();
System.out.println("You must enter double values! ");
}
System.exit(0);
return values;
} catch (ArithmeticException ae) {
System.out.println("Arithmetic error! ");
}}
System.exit(0);
} catch (IndexOutOfBoundsException ioob) {
System.out.println("Three doubles are required! ");
Input:
System.exit(0); Enter the loan amount: Bart
}} Output:
You must enter double values!
35
Conclusions
• Recognizing error types
• Exceptions
• Debugging Your Applications
• Testing Your Applications
36