0

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?

Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
user755806
  • 6,565
  • 27
  • 106
  • 153
  • Erm, you can't throw `null`? Do you mean to *return* `null`? – meriton Dec 19 '13 at 10:26
  • @meriton You can `throw null`. Check [this](http://stackoverflow.com/questions/17576922/why-can-i-throw-null-in-java) – Aman Arora Dec 19 '13 at 10:34
  • Since `null` isn't an instance of `Throwable`, it can not be thrown, or caught. While `throw null` compiles, it doesn't actually throw `null`, but a new `NullPointerException` (when I say "throw x", I mean what the spec calls "complete abruptly, the reason being a throw with value x".) – meriton Dec 19 '13 at 11:00

2 Answers2

1

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.

Pieter
  • 895
  • 11
  • 22
1

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.

Aman Arora
  • 1,232
  • 1
  • 10
  • 26