我需要为Java程序编写一个自定义异常类。例如,在尝试从列表中删除现有产品时,应抛出一个带有“错误”的语句的异常。我尝试过使用它,但我不知道它是否正确。
public class ProductException extends RuntimeException
{
public ProductException(String message)
{
super(message);
}
}
public class ShoppingCart
{
public void removeFromCart(Product p) throws ProductException
{
int i = cart.indexOf(p);
if (i >= 0)
{
cart.remove(p);
}
else
{
ProductException e = new ProductException("Error..Product not found");
}
}
}
这里有什么错误以及如何纠正错误?谢谢。
您已经创建了对异常对象的引用,但是您没有对它做任何事情。你需要做的是throw
异常。
如您所知,在哪里创建ShoppingCart
对象并使用Product
对象填充它,您可以在该removeFromCart(...)
对象上调用cart
来执行所需的操作。您的调用代码的基本示例是:
ShoppingCart cart = new ShoppingCart();
Product apple = new Product();
cart.addToCart(apple);
cart.removeFromCart(apple);
在这里,我们创建对象并使用它或在其上执行某些操作。在您的示例代码中,问题是您没有对您创建的对象执行任何操作,因此它会立即超出范围并标记为垃圾回收。
异常与其他对象略有不同,因为您不必创建引用对象来使用它(与上面的ShoppingCart
一样)。你要做的是创建Exception,但是我们需要抛出并捕获Exception,如下所示,它将为我们隐式创建它:
public class ProductException extends RuntimeException
{
public ProductException(String message)
{
super(message);
}
}
public class ShoppingCart
{
public void removeFromCart(Product p) throws ProductException
{
int i = cart.indexOf(p);
if (i >= 0) {
cart.remove(p);
} else {
throw new ProductException("Error..Product not found");
}
}
}
我们刚才提出的例外需要被调用removeFromCart(...)
的范围。例如:
public static void main(String[] args)
{
ShoppingCart cart = new ShoppingCart();
Product orange = new Product();
cart.addToCart(orange);
try {
cart.removeFromCart(orange);
} catch (ProductException ex) {
/*
Do something... For example, displaying useful information via methods such
as ex.getMessage() and ex.getStackTrace() to the user, or Logging the error.
*/
} catch (Exception ex) {
// Do something...
}
}
如果您仍然不确定或需要更多内容,我建议您从Oracle Docs页面上的Java 'How to Throw Exceptions' tutorial开始,在那里您可以了解有关异常以及抛出和捕获它们的过程的更多信息,以及相关的try
,catch
和finally
块。
您需要在else块中抛出异常:
ProductException e=new ProductException("Error..Product not found");
throw e;
现在,您可以在调用函数中处理此异常。
这是建议抛出异常的实现:
public class ShoppingCart
{
public void removeFromCart(Product p) throws ProductException
{
if (!cart.contains(p))
{
throw new ProductException("Error..Product not found");
}
cart.remove(p);
}
}