Home > Java > javaTutorial > body text

How java throws exceptions suitable for abstraction

PHPz
Release: 2023-04-28 14:40:10
forward
1476 people have browsed it

Throw exceptions suitable for abstraction

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);
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template