因此,我有一种方法,可以通过键盘上的userInput插入计算器。显然,我不能在输入字段中放入字符串或负数,因此我将所有三个输入都封装在try块中以捕获任何异常。问题是我尝试在try块内输入错误时抛出异常,但是当捕获到异常时,它将显示try-catch块的消息。这是代码:
public static void calculateTips()
{
//Varibles
int tipPercentage = 0;
int partySize = 0;
double billAmount = 0.0;
//Variable to loop through try catch blocks
int x = 0;
String yesOrNo;
boolean choice;
//Decimal Format
DecimalFormat dollar = new DecimalFormat("$###,##0.00");
//Declare object
TipCalculator bill;
//Create Scanner object
Scanner userInput = new Scanner(System.in);
do
{
//Fill values for tip calculator from user
System.out.println("Enter the bill amount: ");
try
{
billAmount = userInput.nextDouble();
if(billAmount < 0)
throw new Exception("Bill amount can not be negative. Please try again.");
System.out.println("Enter your desired tip percentage (20 equals 20%): ");
tipPercentage = userInput.nextInt();
if(tipPercentage < 0)
throw new Exception("Tip percentage can not be negative. Please try again.");
System.out.println("Enter the size of your party: ");
partySize = userInput.nextInt();
if(partySize < 0)
throw new Exception("Party Size can not be negative. Please try again.");
}
catch(Exception e)
{
System.out.println("Invalid Input. Please try again." + "\n");
calculateTips();
}
我曾尝试使用InputMismatchType作为整体异常,但没有运气。如您所见,我正在尝试在try块中显示那些自定义消息。如果有人可以帮助,那就太好了。
答案 0 :(得分:1)
问题是您捕获了Exception
,这意味着任何异常(和异常的子类)都将被捕获在同一块中,一种解决方案是创建一个自定义异常并比捕获其他异常的异常更早地捕获它默认为这样:
try {
billAmount = userInput.nextDouble();
if(billAmount < 0)
throw new MyException("Bill amount can not be negative. Please try again.");
} catch(MyException e) { // catch a specific exception first
System.out.println("Exception" + e.getLocalizedMessage());
} catch(Throwable e) { // get all others to fall here, also using Throwable here cause it is also super for Exception and RuntimeException
System.out.println("Invalid Input. Please try again." + "\n");
calculateTips();
}
// and declare in the scope of class
class MyException extends Exception {
MyException(String message) { super(message); }
}
另一种解决方案是在捕获中捕获特定的ArithmeticExceptions和ParseExceptions并针对您的特定错误使用第三个(在两种情况下仍建议扩展一个)