The exception thrown should be related to the task performed by the caller. This item introduces exception conversion (catching an exception and throwing another one) and exception chaining (wrapping an exception in a new exception to preserve the exception's causal chain).
private void serializeBillingDetails(BillingResult billingResult, BillingDetailsType billingDetails) { try { final JAXBContext context = JAXBContext .newInstance(BillingdataType.class); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final Marshaller marshaller = context.createMarshaller(); marshaller.setProperty("jaxb.formatted.output", Boolean.FALSE); final BillingdataType billingdataType = new BillingdataType(); billingdataType.getBillingDetails().add(billingDetails); marshaller.marshal(factory.createBillingdata(billingdataType), out); final String xml = new String(out.toByteArray(), "UTF-8"); billingResult.setResultXML(xml.substring( xml.indexOf("<Billingdata>") + 13, xml.indexOf("</Billingdata>")).trim()); billingResult.setGrossAmount(billingDetails.getOverallCosts() .getGrossAmount()); billingResult.setNetAmount(billingDetails.getOverallCosts() .getNetAmount()); } catch (JAXBException | UnsupportedEncodingException ex) { throw new BillingRunFailed(ex); } }
The above method catches JAXBException
and UnsupportedEncodingException
and rethrows a new exception appropriate for the method's abstraction level. The new BillingRunFailed
exception wraps the original exception. So this is a good example of exception chaining. The benefit of exception chaining is that it preserves low-level exceptions that can be helpful in debugging problems.
The above is the detailed content of How java throws exceptions suitable for abstraction. For more information, please follow other related articles on the PHP Chinese website!