首页 > 解决方案 > 对异常抛出和异常处理感到困惑

问题描述

我正在学习异常和异常处理,但如果我做得对,我会有点困惑。下面是我正在处理的构造函数,如果参数不匹配,它会抛出 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" );
        
    }

标签: javaexceptionjunit

解决方案


您不应该在构造函数中捕获异常,而是抛出它们。以第一种情况为例:

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/


推荐阅读