gpt4 book ai didi

java - 无法捕获算术异常(不过捕获 IllegalArgumentException 没问题)

转载 作者:行者123 更新时间:2023-12-01 23:11:55 30 4
gpt4 key购买 nike

请看下面我的构造函数,我正在从字符串创建一个分数:

public Fraction(String str)
{
if(str.isEmpty())
{
throw new IllegalArgumentException("The str (String) parameter cannot be empty!");
}
int[] fractionData= new int[2];
String[] data = str.split("/");
try
{
if(data.length==0)
throw new IllegalArgumentException("The str (String) parameter cannot be empty");
}
catch (IllegalArgumentException ex)
{
System.out.println(ex.toString());
}
try
{
fractionData[0] = Integer.parseInt(data[0]);
}
catch (IllegalArgumentException ex)
{
System.out.println(ex.toString());
}

try
{
fractionData[1] = Integer.parseInt(data[1]);
if(fractionData[1]==0) throw new ArithmeticException("Denominator can't be 0");
}
catch (ArithmeticException ex)
{
System.out.println(ex.toString());
}
fractionData = normalize(fractionData[0],fractionData[1]);
this.numerator = fractionData[0];
this.denominator = fractionData[1];
}

我很好地捕获了 IllegalArgumentException,但未能捕获 ArithmticException。我可以成功测试两者

@Test(expected=IllegalArgumentException.class)
public void testIllegalArgumenException() throws IllegalArgumentException
{
Fraction g = new Fraction("");
}
@Test(expected=ArithmeticException.class)
public void testArithmeticException() throws ArithmeticException
{
Fraction g = new Fraction(1/0);
}

感谢@xp500的评论,我已将代码更改为:

public Fraction(String str)
{
if(str.isEmpty()) throw new IllegalArgumentException("The str (String) parameter cannot be empty!");
int[] fractionData= new int[2];
String[] data = str.split("/");
if (data.toString().matches("[a-zA-Z]+")) throw new NumberFormatException("only numbers allowed in the string");
fractionData[0] = Integer.parseInt(data[0]);
fractionData[1] = Integer.parseInt(data[1]);
if(fractionData[1]==0) throw new ArithmeticException("Denominator can't be 0");
fractionData = normalize(fractionData[0],fractionData[1]);
this.numerator = fractionData[0];
this.denominator = fractionData[1];
}

它不会引用“仅字符串中允许的数字”,但会停止将分数初始化为 0/0,以防使用带有字母的字符串来初始化分数,并抛出带引号文本的其他异常。我学到的教训是:不要捕捉异常,除非你实际上正在对它们做一些事情

最佳答案

你正在捕获ArithmeticException,但你没有追溯它(像其他异常一样)

关于java - 无法捕获算术异常(不过捕获 IllegalArgumentException 没问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21803591/

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