[英]Java: How to create an Exception Hashtable?
在我教授的建議下,我試圖創建一個要在我的服務異常類中使用的異常哈希表。 我目前在哈希表中創建值時遇到問題。
到目前為止,我嘗試不創建變量,但是這導致無法解決我的異常。 我已經創建了變量,但是需要實例化它們,但是,null會導致NullPointException
而= new Exception()會導致(示例) "e1=java.lang.Exception"
。
public class HashtableException {
public static void main(String[] args) {
Hashtable <String, Exception> exceptionHashtable =
new Hashtable <String, Exception>();
Exception FileNotFoundException;
Exception IOException;
Exception ObjectStreamException;
Exception ClassNotFoundException;
Exception FileFormatException;
Exception NoSuchFieldException;
exceptionHashtable.put("e1", FileNotFoundException);
exceptionHashtable.put("e2", IOException);
exceptionHashtable.put("e3", ObjectStreamException);
exceptionHashtable.put("e4", ClassNotFoundException);
exceptionHashtable.put("e5", FileFormatException);
exceptionHashtable.put("e6", NoSuchFieldException);
System.out.println("The Hashtable is:" + exceptionHashtable);
} // end main method
} // end class HashtableException
顯示哈希表應該導致:
The Hashtable is:{e1=FileNotFoundException, e2=IOException,...}
但實際輸出為:
The Hashtable is:{e6=java.lang.Exception, e5=java.lang.Exception,...}
我將您的代碼更改為以下代碼,現在可以使用了。 但是,其中兩個沒有用,所以我發表了評論。 您需要弄清楚需要做什么
FileNotFoundException fileNotFoundException= new FileNotFoundException();
IOException ioException = new IOException();
//ObjectStreamException objectStreamException = null;
ClassNotFoundException classNotFoundException= new ClassNotFoundException();
//FileFormatException FileFormatException;
NoSuchFieldException noSuchFieldException = new NoSuchFieldException();
exceptionHashtable.put("e1", fileNotFoundException);
exceptionHashtable.put("e2", ioException);
//exceptionHashtable.put("e3", objectStreamException);
exceptionHashtable.put("e4", classNotFoundException);
//exceptionHashtable.put("e5", FileFormatException);
exceptionHashtable.put("e6", noSuchFieldException);
System.out.println("The Hashtable is:" + exceptionHashtable);
輸出是
哈希表是:{e6 = java.lang.NoSuchFieldException,e4 = java.lang.ClassNotFoundException,e2 = java.io.IOException,e1 = java.io.FileNotFoundException}
因為您是在尋求家庭作業的幫助,所以我將給出含糊但(希望)有用的提示和一般性解釋。
變量是一個可以容納東西的桶。 在表達式中使用變量時,您是在要求存儲桶中的東西為您完成一些任務。
當存儲桶為空時,它不包含任何東西。 嘗試使用該存儲桶進行工作是沒有意義的,因為您實際上是在問存儲桶中的東西- 沒什么 。 null
表示存儲桶不包含任何內容,並且如果您嘗試對其進行某些操作(除了檢查null
),則將收到NullPointerException
。
您還混淆了你的類型變量的名稱 。 命名變量'IOException'並不意味着它實際上是IOException
。 您已經創建了一個類型為Exception
的變量,其名稱會使任何查看它的人都對變量的類型感到困惑。 由於您似乎想引用IOException
類,因此請嘗試在此處查找: Class類以及類文字 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.