i create an android application. and typed some codes just like :
public void onCreate(Bundle savedInstanceState) {
...
XmlResourceParser xrp = getResources().getXml(R.xml.OneXml); <==OneXml is a custom xml file in folder res/xml
...
try {
....
xrp.next();
....
} catch(IOException e) {
e.printStackTrace();
} catch(XmlPullParserException e) {
e.printStackTrace();
}
...
i found that i can neither delete catch(IOException e) nor catch(XmlPullParserException e), when i try to delete one of them, Eclipse marks an error at xrp.next() and tells me that Unhandled exception type IOException or Unhandled exception type XmlPullParserException, so must i add the two catch? why does Eclipse ask me to add two catch compulsively? Can’t the code be compiled successfully without the two catch?
Exception Handling ways:
We can handle a ‘problem statement’ (Problem Statement is any statement which can throw an exception) in two ways.
try-catchblock.throwsclause in the method header.Handling Exception in Overridden Methods:
If you are overriding a method in child class. Then you cannot append extra throws clause in its signature. In your case
onCreateis a method in parent class, which is overridden in child class hence we can not append throws clause in it header. So you have to enclose any ‘Problem Statements’ withinonCreatemethod in try-catch blocks.Examples:
Enclose the statement in
try-catchblock.Append a
throwsclause in the method header.Examples Overridden Methods:
Valid throws clause: A throws clause in overridden method is valid if it is also in parent’smethod.
Invalid throws clause: A throws clause in overridden method is invalid if it is not present in parent’s method.
So we have to modify our child class’s method and remove
throwsclause as parent method do not contain throws clause in this particular situation. We have to handle exception throughtry-catchblock.