你好,我有一个编程任务,我必须使用他们给我们的函数,因为他们把它交给我们使用,我遇到的问题是这个函数必须是空的,并且我不允许使用System.out.println();所以我的问题是如何在不更改方法头或使用System.out.println()的情况下返回异常?
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
System.out.println("ITEM " + itemID + " DOES NOT EXIST!");
}
}
发布于 2016-04-25 19:27:17
您可以更改方法签名并引发异常
public void deleteItem(String itemID) throws Exception{
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}catch (IndexOutOfBoundsException e) {
Exception ex = new Exception("ITEM " + itemID + " DOES NOT EXIST!");
throw ex;
}
}
完成后,您会得到如下的错误消息
try{
xxx.deleteItem("your itemID");
}catch(Exception e){
// You will read your "ITEM " + itemID + " DOES NOT EXIST!" here
String yourErrorMessage = e.getMessage();
}
发布于 2016-04-25 19:28:52
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException( "ITEM " + itemID + " DOES NOT EXIST!");
}
}
public void deleteItem(String itemID)throws IndexOutOfBoundsException{
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
你不能返回异常。方法抛出异常,您可以使用上述方法的that.try关键字throw
抛出方法中的异常
发布于 2016-04-25 19:30:25
在catch块中执行以下操作:
catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException("ITEM " + itemID + " DOES NOT EXIST!");
}
您不需要向方法添加抛出声明,因为IndexOutOfBoundsException是一个RuntimeException。
在调用函数的任何地方,都可以添加catch块来读取错误消息,如下所示:
catch (IndexOutOfBoundsException ex) {
System.out.println(ex.getMessage());
}
https://stackoverflow.com/questions/36839191
复制相似问题