java - 对异常抛出和异常处理感到困惑
问题描述
我正在学习异常和异常处理,但如果我做得对,我会有点困惑。下面是我正在处理的构造函数,如果参数不匹配,它会抛出 IllegalArgumentExceptions。
/**
* Initializes this chair to the specified fields
*
*
* @param chairManufCost the chair manufacturing cost
* @param chairShape the chair shape
* @param chairColor the chair color
*
* @pre.
* <p> <strong> Precondition </strong> </p>
* <p> The chair color should be one of the following choices ,
* <strong><code>{black or white} </code></strong>,</p>
* <p><strong>It should be noted that colors
* string comparisons are carried out with case insensitive
* For example, these strings are equals "black", "Black", "BLACK",...</strong> </p>
*
* <p>
* The chair shape should be one of the following choices
* <strong><code>{Rectangle or Square} </code></strong>,</p>
* <p><strong>It should be noted that shapes
* string comparisons are carried out with case insensitive
* For example, these strings are equals "Rectangle", "RECtangle", "RECTANGLE",...</strong> </p>
* <p> and, the chair manufacturing cost should be positive real number
* </p>
*
* @throws IllegalArgumentException
* <p> if the manufacturing Cost of chair is negative value </p>
*
*
* @throws IllegalArgumentException
* <p>if the chair color is not one of possible chair colors</p>.
*
* @throws IllegalArgumentException
* <p> if the chair shape is not one of the possible chair shapes </p>
*
*
*
*
*
*
*
*/
public Chair(double chairManufCost, String chairShape, String chairColor) {
// COMPLETE THIS
try {
this.chairManufCost = chairManufCost;
}
catch(IllegalArgumentException e)
{
System.out.print("The manufacture cost cannot be a negative value");
}
try{
this.chairShape = chairShape;
}
catch(IllegalArgumentException r)
{
System.out.print("The chair shape must be either Square or Rectangle");
}
try {
this.chairColor = chairColor;
}
catch(IllegalArgumentException t)
{
System.out.print("the chair color must either be black or square");
}
numChairs++;
}
接下来是我运行的 Junits 测试来测试它,但失败说“java.lang.AssertionError:预期异常:java.lang.IllegalArgumentException”,我不确定我这样做是否正确,请有人解释或尝试帮助我弄清楚我做错了什么,请谢谢。
@Test(expected = IllegalArgumentException.class)
public void test03a_ctor() {
Chair ch = new Chair(120,"Cylinder", "black" );
}
解决方案
您不应该在构造函数中捕获异常,而是抛出它们。以第一种情况为例:
if(chairManufCost < 0) {
throw new IllegalArgumentException("The manufacture cost cannot be a negative value")
}
this.chairManufCost = chairManufCost;
我想您搜索一些有关 Java 异常的文档,例如https://docs.oracle.com/javase/tutorial/essential/exceptions/
推荐阅读
- excel - vba函数返回单元格背景颜色
- sql - kotlin 与 jooq 并手动编写表模型,无需代码生成
- c# - 使用 httpwebrequest 和 cookie 下载的 c# 文件已损坏
- python - 使用 for 循环在 python 的字典中打印键和/或值。寻找逻辑思维解释谢谢:D
- apache - 如何使用 .htaccess 缓存 woff 文件
- python - 如何将每个白色斑点与我的 png 图像分开?
- jquery - 单独控制多个表
- flexbox - 根据分辨率更改 Angular 材质按钮样式
- php - 使用 mysql 和 php 显示所有电影列表
- regex - 将 bash =~ 运算符更改为与 sh 兼容的参数