gpt4 book ai didi

java - 如何显示自定义的 throw 语句

转载 作者:行者123 更新时间:2023-11-30 05:34:59 25 4
gpt4 key购买 nike

所以我有一种方法,可以将键盘上的用户输入插入计算器。显然,我不能将字符串或负数放入输入字段中,因此我将所有三个输入都包含在 try block 中以捕获任何异常。问题是,当 try block 内的输入错误时,我试图抛出异常,但是当捕获异常时,它会显示 try-catch block 的消息。这是代码:

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 block 中显示这些自定义消息。如果有人能提供帮助那就太好了。

最佳答案

问题是你捕获了Exception,这意味着任何异常(以及excption的子类)都将在同一个 block 中捕获,解决方案是创建一个自定义异常并早于异常捕获它将其他异常(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,并针对特定错误使用第三个异常(在这两种情况下仍然建议扩展一个)

关于java - 如何显示自定义的 throw 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56838870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com