簡體   English   中英

使用我創建的Exception類捕獲拋出的異常

[英]Catching thrown exceptions with an Exception class I created

GraphicsFileNotFoundException.java我所有的都是FileNotFoundException的導入和擴展FileNotFoundException GraphicsFileNotFoundException類。

在我的主java文件中,我試圖用圖形文件讀取getGraphicsFile方法,該方法拋出GraphicsFileNotFoundException

經過40分鍾的努力,我的大腦陷入困境,試圖找出如何捕獲這個異常。 我已經嘗試使用try-catch塊並捕獲GraphicsFileNotFoundException但我仍然得到錯誤

unreported exception GraphicsFileNotFoundException ; must be caught
   or declared to be thrown.



public void getGraphicsFile(String fileName) throws GraphicsFileNotFoundException {
    String graphics = "";
    Scanner getGraphics = null;
    try { 
      getGraphics = new Scanner(new File(fileName));
    }

    catch (GraphicsFileNotFoundException e){
      System.out.println("Error! File can't be found :/");
    }

您需要正確擴展FileNotFoundException類或手動在try塊中引發異常。

假設這是一個賦值(我不確定為什么你還需要專門擴展這個異常),你需要再看一下你的GraphicsFileNotFoundException類,並確保它做了它需要的東西。

要拋出異常,只需編寫條件和throw語句:

if(needToThrow) {
    throw new GraphicsFileNotFoundException();
}

要捕獲異常,請使用try塊然后緊跟catch塊來包圍throw語句。

try {
    // code here
    if(needToThrow) {
        throw new GraphicsFileNotFoundException();
    }
}
catch(GraphicsFileNotFoundException e) {
    // handle the error (print stack trace or error message for example)
    e.printStackTrace(); // this is printing the stack trace
}

如果您還沒有使用Eclipse,我建議使用Eclipse ,因為很多時候它會提供需要使用自動生成的try catch塊捕獲的環繞聲拋出語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM