簡體   English   中英

Java嘗試捕捉異常

[英]Java Try Catch Exception

我當前的代碼塊返回如下異常:

Exception occurred in API invocation A1-123 Fatal error
Caused by: A9-001 ColName is not found in TableName

但我想...

  1. 擺脫A1 Exception
  2. 直接顯示A9 Exception
  3. 不顯示A9 ExceptionCaused by

我如何使異常看起來像這樣?

Exception occurred in API invocation A9-001 ColName is not found in TableName
<no Caused by clause>

這是我的示例代碼:

public Sample Method (Input input) throws AException
{
   con = getSQLConnection();

   try{
      //do something
      if(x==null){
         throw new AException(A9ErrorMessages.A9_ERROR_FROM_TABLE, new String [] { "ColName", "TableName"});
      }
   }
   catch (Exception e){
      logger().error(e);
      throw new AException(e);
   }
   finally{
      if(con!=null){
         try{
            con.close();
         }
         catch(Exception e){
            logger().error(e);
            throw new AException(e);  
         }
      }
   }
}

如果它是這樣的,它會起作用嗎:

   try{
      //do something
   }
   catch (Exception e){
      logger().error(e);
      throw new AException(A9ErrorMessages.A9_ERROR_FROM_TABLE, new String [] { "ColName", "TableName"});
   }
   catch (Exception e){
      logger().error(e);
      throw new AException(e);
   }

我假設您要捕獲並傳遞的錯誤是AException - 否則您所要求的將違反該方法的約定。 您可以使用像這樣的額外catch子句來實現您想要的。

try {
    // whatever
}
catch (AException ae) {
    throw ae;
}
catch (Exception e){
  logger().error(e);
  throw new AException(e);
}
finally {
     // whatever
}

這樣,只有不是AException類型的AException才會被包裝在新的AException對象中。

第一個評論者是正確的。 我能夠通過創建一個新的第一個捕獲來做到這一點:

public Sample Method (Input input) throws AException
{
   con = getSQLConnection();

   try{
      //do something
      if(x==null){
         AException ae = new AException(A9ErrorMessages.A9_ERROR_FROM_TABLE, new String [] { "ColName", "TableName"});
         logger().error(ae);
         throw ae;
      }
   }
   catch (AException ae){
      logger().error(ae);
      throw ae;
   }
   catch (Exception e){
      logger().error(e);
      throw new AException(e);
   }
   finally{
      if(con!=null){
         try{
            con.close();
         }
         catch(Exception e){
            logger().error(e);
            throw new AException(e);  
         }
      }
   }
}

暫無
暫無

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

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