views:

67

answers:

2

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. P.S. I know that using general exception is not good practice, its just for example purpose here.

+1  A: 

The first approximation for solving that problem is usually to put the logic of the catch in a separate method, and only have one line in the catch block (the method call).

Yishai
+1 for typing faster ;-)
Péter Török
Had similar idea, so I guess i just stick to it.
artjomka
A: 

Always catch specific exceptions, not the general Exception superclass.

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 ...")
}
Riaan Cornelius