java - Handling org.xml.sax.SAXParseException while reading and writing an XML file using JAXB -
i'm creating xml file using jaxb follows.
public final class main { private file file; private transient jaxbcontext jaxb; list<fruit>fruits; private void test() { try { jaxb=jaxbcontext.newinstance(fruits.class); file=new file(system.getenv("upload_location")+"\\xml_files\\fruits.xml"); marshaller marshaller = jaxb.createmarshaller(); marshaller.setproperty(marshaller.jaxb_formatted_output, boolean.true); marshaller.setproperty(marshaller.jaxb_encoding, "utf-8"); marshaller.setproperty(marshaller.jaxb_fragment, boolean.false); if(!file.exists()) { file.createnewfile(); marshaller.marshal(new fruits(new arraylist<fruit>()), file); } else { fruits=((fruits) jaxb.createunmarshaller().unmarshal(file)).getlist(); } for(fruit fruit:fruits) { system.out.println(fruit.getid()+" : "+fruit.getname()+" : "+fruit.getprice()); } } catch (jaxbexception ex) { logger.getlogger(main.class.getname()).log(level.severe, null, ex); } catch (ioexception ex) { logger.getlogger(main.class.getname()).log(level.severe, null, ex); }/*catch (saxparseexception ex) { logger.getlogger(main.class.getname()).log(level.severe, null, ex); }*/ } public static void main(string... args) { new main().test(); } } the code adds objects excluded. generates xml file following.
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <fruits> <fruit id="1"> <name>mango</name> <price>100</price> </fruit> <fruit id="2"> <name>banana</name> <price>50</price> </fruit> <fruit id="3"> <name>pineapple</name> <price>80</price> </fruit> </fruits> if xml file invalidated reasons, may modified externally.
if file contains mulformed xml format then, throws org.xml.sax.saxparseexception. if exception thrown then, want recreate file. otherwise, exception thrown continually unless xml contents manually modified , restructured. so, exception should caught.
the compiler refuses catch exception. if additional catch block exception attempted shown in code snipped then, complains,
exception
org.xml.sax.saxparseexceptionnever thrown in body of correspondingtrystatement
how handle exception file can recreated (deleting old one) in case, exception thrown?
i'm not showing classes (fruit , fruits) create xml elements, since not quite related question.
saxparseexception checked exception , not declared on method unmarshal(), it's normal cannot catch it.
there exception catch, javax.xml.bind.unmarshalexception. exception extends javax.xml.bind.jaxbexception have put catch block before jaxbexception.
in documentation of method unmarshal() says unmarshalexception thrown, if validation error occurs or unmarshaller unable perform xml java binding.
note: verified in implementation of unmarshaller , when an
org.xml.sax.saxexception occurs, wrapped in javax.xml.bind.unmarshalexception.
Comments
Post a Comment