Exception object
It is not unusual that a piece of code throws a number of exceptions. One way to handle this situation is to try-catch all exceptions and then use the exception
object to determine what issue has happened and to output information from the Exception
to debug the problem.
Here, you will modify the SplitTheBill
application again to catch
a generic Exception
and use data from the Exception
object to understand the cause of the problem. Exception
objects contain a lot of useful information including a trace of methods leading to the problem.
This exercise is part of the course
Data Types and Exceptions in Java
Exercise instructions
- In the catch block capture any
Exception
usingcatch (Exception e)
. - Use the
Exception
and object reference (e
) and thegetClass()
method in thecatch
block to display the type (class) of exception caught. - Use the
Exception
object reference (e
) and thegetMessage()
method to print the exception's message. - Print the "stack trace" to output stream using the
Exception
object reference (e
) and theprintStackTrace()
method.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.math.BigDecimal;
class SplitTheBill {
public static void main(String[] args) {
BigDecimal bill = new BigDecimal(125.50);
computeEachBill(bill, 5);
computeEachBill(bill, 0);
}
public static void computeEachBill(BigDecimal bill, int people) {
try {
BigDecimal numPeople = new BigDecimal(people);
BigDecimal individualBill = bill.divide(numPeople);
System.out.println("Bill for each person is: " + individualBill);
// Catch any exception
} catch (____ ____) {
System.out.println("You didn't provide a positive number of people to split the bill among.");
// Print the type (class) of exception
System.out.println("Type of exception: " + ____.____());
// Print the exception message
System.out.println(____.____());
// Print the stack trace
____.____();
}
}
}