正如標題所示,我試圖捕捉一個空字符串。我有一個類(我嘗試創建的對象的類)在String爲空或空時引發異常(使用str.isEmpty檢查)。 當我嘗試在另一個類中使用空字符串創建對象時,它按預期工作並引發異常。但是,我希望此類能夠捕獲該異常並通知用戶。但它似乎從來沒有捕捉異常,即使我嘗試寫Catch(Exception exc)。 現在我知道null或空字符串不是非法的。但我的意圖是,對象類應該是這樣做的。相反,它看起來好像是catch塊根本不在乎。我開始認爲我將不得不創建自己的某種類型的異常類......或者是否有我缺少的東西?下面是代碼的相關部分:捕獲空字符串。哪個例外使用?
對象類的構造函數:
public Valueables(String name){
//name.trim().length() == 0
if(name == null || name.isEmpty()){
try {
throw new Exception("Subclasses of Valueables cannot take in an empty String or null value for the \"name\" constructor");
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
else
this.name = name;
}
另一類(新飾品目的是Valueables的子類的一個與上面的構造函數代碼。):
while(loopPassErrorControl == false){
//I don't think the try loop is relevant. But just to make sure...
//Otherwise just ignore it
try{
TrinketForm Tform = new TrinketForm();
answer = JOptionPane.showOptionDialog(ValueablesFrame.this, Tform, "Nytt smycke", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options , null);
if (answer != JOptionPane.OK_OPTION){
return;
}
valueablesList.add(new Trinket(Tform.getName(), Tform.getGemstones(), Tform.getMetalSelected()));
loopPassErrorControl = true;
}catch(NumberFormatException | NullPointerException exc) {
JOptionPane.showMessageDialog(ValueablesFrame.this, "Något gick fel");
}
}
//Test
for(Valueables obj : valueablesList){
System.out.println(valueablesList);
}
如果這是一個非法的參數,爲什麼不'IllegalArgumentException? – 2015-03-31 10:26:52
您是否知道您不必拋出並捕獲異常來打印其堆棧跟蹤? 'new Exception(「message」)。printStackTrace();'也可以。 – 2015-03-31 10:27:47
你在哪裏叫'新的有價值(名稱)'? – 2015-03-31 10:31:47