[英]Java Try Catch Exception
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...但我想...
A1 Exception
摆脱A1 Exception
A9 Exception
directly直接显示A9 Exception
A9 Exception
in Caused by
不显示A9 Exception
在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);
}
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.我假设您要捕获并传递的错误是AException
- 否则您所要求的将违反该方法的约定。 You could achieve what you're wanting with an extra catch
clause like this.您可以使用像这样的额外catch
子句来实现您想要的。
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.这样,只有不是AException
类型的AException
才会被包装在新的AException
对象中。
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);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.