Skip to content Skip to sidebar Skip to footer

Do I Have To Include Catch Blocks In Java When Calling A Method That Throws Exceptions?

i create an android application. and typed some codes just like : public void onCreate(Bundle savedInstanceState) { ... XmlResourceParser xrp = getResources().getXml(R.xml.OneXml);

Solution 1:

Exception Handling ways: We can handle a 'problem statement' (Problem Statement is any statement which can throw an exception) in two ways.

  • Enclose the statement in try-catch block.
  • Append a throws clause 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 onCreate is 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' within onCreate method in try-catch blocks.

Examples: Enclose the statement in try-catch block.

public void myMethod(){
        try{
            // Problem Statement
        }catch(IllegalAccessException e){
            e.printStackTrace();
        }catch(NullPointerException e){
            e.printStackTrace();
        }
    }

Append a throws clause in the method header.

publicvoidmyMethod()
        throws IllegalAccessException, NullPointerException{
            // Problem Statement
    }

Examples Overridden Methods:Valid throws clause: A throws clause in overridden method is valid if it is also in parent'smethod.

publicclassParent {
    publicintmethod()throws IllegalAccessException,NullPointerException, Exception {
        return0;
    }
}
publicclasschildextendsParent {
    // throws is part of method because parent method// have throws clause@Overridepublicintmethod()throws IllegalAccessException, NullPointerException,
            Exception {
            //Problem Statementreturnsuper.method();
    }
}

Invalid throws clause: A throws clause in overridden method is invalid if it is not present in parent's method.

publicclassParent {
    publicintmethod(){
        return0;
    }
}

publicclasschildextendsParent {
    //**Error:** We can not append throws clause in the method because// parent method do not have a throws clause@Overridepublicintmethod()throws IllegalAccessException, NullPointerException,
            Exception {
            //Problem Statementreturnsuper.method();
    }
}

So we have to modify our child class's method and remove throws clause as parent method do not contain throws clause in this particular situation. We have to handle exception through try-catch block.

publicclasschildextendsParent {
    //**Error:** We can not append throws clause in the method because// parent method do not have a throws clause@Overridepublicintmethod() {
        try{
            // Problem Statement
        }catch(IllegalAccessException e){
            e.printStackTrace();
        }catch(NullPointerException e){
            e.printStackTrace();
        }
    }
}

Solution 2:

In Java you have to either catch exceptions or declare the fact that calling the method might result in an exception, like so:

publicvoidonSomethingOtherThanCreate(Bundle savedInstanceState)throws IOException, XmlPullParserException
{
   // your code without any try/catch
} 

(Error and RuntimeException exceptions which can happen any time do not need to be declared in this way.)

Solution 3:

It's not Eclipse, it's Java!

In a method, code which throws exceptions must reside inside a try-catch block unless the throws clause for the unhanded exception is used in the method declaration itself.

Solution 4:

That's what checked exceptions mean: you must either catch them, or declare them thrown.

onCreate is being overridden and must adhere to the original method's declaration, so either catching them, or doing that part of the work in another method that catches them, is your only option.

See JLS 11 Exceptions, specifically JLS 11.2.3 Exception Checking, for details.

Solution 5:

If your complaint is that you have to type two catch clauses, it is possible to catch them all in a single clause,

catch (Exception e) {
      // dostuff here
   }

However, unless all you plan to do is print a stack trace or log the exception, this practice is frowned upon. In the long run it will make the code harder to debug and maintain.

Java 7 allows you to catch multiple exceptions in a single clause, but Android doesn't yet support Java 7.

Post a Comment for "Do I Have To Include Catch Blocks In Java When Calling A Method That Throws Exceptions?"