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.
Diese Übung ist Teil des Kurses
Data Types and Exceptions in Java
Anleitung zur Übung
- 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.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
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
____.____();
}
}
}