简体   繁体   English

在异常块中处理异常

[英]Handling exceptions in exception block

Could someone please provide some good practice to handle exceptions in exception for example I have 有人可以提供一些良好的做法来处理异常,例如我有

 try { 
 ... 
 DeserializationResult deserialization = xmlSerializationService.deserializeFromXml(node);
 some code here
} catch (Exception e) { 

try {

//I need to create process result xml with error code and some details
// creation of result xml document 

} catch (Exception e) {

// maybe some error message here

  }

}   

can I somehow make this code looks clearer, noiseless and easier to understand? 我能以某种方式使这段代码看起来更清晰,更安静并且更易于理解吗? Thanks for answers. 感谢您的回答。 PS I know that using general exception is not good practice, its just for example purpose here. PS我知道使用一般异常不是一个好习惯,这里只是出于示例目的。

解决该问题的第一个近似值通常是将catch的逻辑放在单独的方法中,并且catch块中只有一行(方法调用)。

Always catch specific exceptions, not the general Exception superclass. 始终捕获特定的异常,而不是常规的Exception超类。

If I look at that code, I'm not sure what can go wrong. 如果我看那个代码,我不确定会出什么问题。 If you specifically catch exceptions, it's much easier to see what failures you are expecting and catering for. 如果您专门捕获异常,则可以轻松地看到预期的故障并解决这些故障。

Also handle each failure in a specific way that makes sense for that failure. 还要以有意义的特定方式处理每个故障。 The simplest form of that is to return a result that describes the failure. 最简单的形式是返回描述失败的结果。

Maybe something like: 也许像这样:

try{
    //DeserializationResult deserialization = xmlSerializationService.deserializeFromXml(node);
    //some code here
}catch(NullPointerException npe){
    //Maybe return something like: new DeserializationResult("xmlSerializationService not initialized")
}catch(DeserializationException dse){
    //Maybe return something like: new DeserializationResult("Could not deserialize because ...")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM