Home > Mobile >  Java Try Catch Exception
Java Try Catch Exception

Time:10-28

My current block of codes returns an exception like:

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

but I would like to...

  1. get rid of A1 Exception
  2. show A9 Exception directly
  3. not show A9 Exception in Caused by

How do I make the exception look like this?

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

This is my sample code:

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);  
         }
      }
   }
}

Would it work if it's something like this:

   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);
   }

CodePudding user response:

I'm assuming the error that you want to catch and pass on is an AException - otherwise what you're asking for would violate the contract of the method. You could achieve what you're wanting with an extra catch clause like this.

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

That way, only exceptions that are not already of type AException will get wrapped in new AException objects.

CodePudding user response:

the first commenter is correct. i was able to do it by creating a new first catch:

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);  
         }
      }
   }
}
  • Related