user755806
user755806

Reputation: 6815

Handling Checked and unchecked exceptions?

I have below class with one method which throws Checked Exception.

public class Sample{

 public String getName() throws CustomException{

  //Some code
   //this method contacts some third party library and that can throw RunTimeExceptions

}

}

CustomException.java

public class CustomException Extends Exception{
 //Some code


}

Now in another class i need to call above the method and handle exceptions.

public String getResult() throws Exception{
  try{
  String result = sample.getName();
   //some code
  }catch(){
     //here i need to handle exceptions
   }
  return result;
}

My requirement is:

sample.getName() can throw CustomException and it can also throw RunTimeExceptions.

In the catch block, I need to catch the exception. If the exception that is caught is RunTimeException then I need to check if the RunTimeException is an instance of SomeOtherRunTimeException. If so, I should throw null instead.

If RunTimeException is not an instance of SomeOtherRunTimeException then I simply need to rethrow the same run time exception.

If the caught exception is a CustomException or any other Checked Exception, then I need to rethrow the same. How can I do that?

Upvotes: 0

Views: 160

Answers (2)

Aman Arora
Aman Arora

Reputation: 1252

You can do like this :

catch(RuntimeException r)
{
     if(r instanceof SomeRunTimeException)
       throw null; 
       else throw r;
}
catch(Exception e) 
{
     throw e;
}

Note: Exception catches all the exceptions. That's why it is placed at the bottom.

Upvotes: 1

Pieter
Pieter

Reputation: 903

You can simply do:

public String getResult() throws Exception {
    String result = sample.getName(); // move this out of the try catch
    try {
        // some code
    } catch (SomeOtherRunTimeException e) {
        return null;
    }
    return result;
}

All other checked and unchecked exceptions will be propagated. There is no need to catch and rethrow.

Upvotes: 1

Related Questions