3

Is it advisable as a practice to wrap an Unchecked exception into a Checked exception?

Why this question?

I am creating an API which wraps all the checked exceptions into an API specific checked exception. So I was wondering whether the unchecked exceptions can also be wrapped in checked exception.

Are there any advises on this? If they can be wrapped, it would be great if illustrated with a situation where it can make sense.

2
  • (I'm not the downvoter but) I just got a "primarily opinion-based: Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise." flag through which I assume came from the same person Commented Nov 25, 2013 at 12:52
  • Whether it is advisable would depend on the circumstances. Commented Nov 25, 2013 at 12:57

4 Answers 4

4

Checked exceptions should be used for conditions from which the caller can reasonably be recovered. By throwing a checked exception, you are forcing the caller to handle the exception in a catch clause or to propagate it outward. The API user can be recovered from the exceptional condition by catching the Exception and taking proper recovery steps.

For example, FileNotFoundException is a checked exception:

try {
    FileInputStream fis = new FileInputStream(file);
    } catch (FileNotFoundException e) {
    // HANDLE THE EXCEPTION
}

Here even if the file is not found, continued execution of the application would be possible if the user has proper recovery steps in place (reading the file from a different location, etc.).

On the other hand, Runtime exceptions should be used to indicate that recovery is not possible and continued execution would do more harm. Many a times, runtime exceptions are used to indicate precondition violations: the contract that has been defined to use your API is violated by the client of your API.

For example, ArrayIndexOutOfBoundsException is a runtime exception:

int[] aa = new int[2];
int ii = aa[2]; // java.lang.ArrayIndexOutOfBoundsException

because the contract to access elements of an array says that array index must be between zero and the array length minus one, and we have violated that precondition above.

Again, suppose you are writing a class Address as below where the areaCode cannot be null. And if anybody creates an Address without an areaCode, it might do more harm in the future while using the Address. Here, you can use IllegalArgumentException (which is a runtime exception) to indicate that:

public class Address {
private String areaCode;

public Address(String areaCode) {
    if (areaCode == null) {
        throw new IllegalArgumentException("Area Code cannot be NULL");
    }
    this.areaCode = areaCode;
}
...
}

So, it is advisable to use checked exceptions wherever recovery is possible, and if recovery is not possible or if there is any precondition violation, it is good to use Runtime exception.

Sign up to request clarification or add additional context in comments.

Comments

0

I am creating an API which wraps all the checked exceptions into an API specific checked exception.

To achieve this, if you are not explicitly having catch(Runtime e) before catch(Exception e), you are anyway wrapping unchecked exception too. Which IMO is generally what is being followed unless there is an specific requirement to treat Runtime exception separately.

It's fine for a service to catch both runtime and checked exception to a service level exception sothat caller would deal with only ServiceException which might have custom attributes, codes etc.

One example could be having a service method which works on IO APIs:

public void serviceA(String path) throws ServiceException {
try {
File f = new File(path); //Runtime - NPE etc
Reader r = .. //Checked IOException, may be some Runtime exception
}catch(Exception e) { //both runtime and checked
throw new ServiceException("CUSTOMMSG", e);
}
}

Here, dealing with Runtime exception would be very specific case as service contract is via ServiceException which caller understands and would not know how to deal with Runtime Exception.

2 Comments

Why are you forcing the user to catch this ServiceException in any case? If the user does not care give him the opportunity to just ignore it!
Yes that may be the case for some services but not for some. For example google has many APIs exposed for various services, some DFA, DFP throws checked exceptions with detailed code, msg, suggests whereas some of its services doesn't.. I don't know a golden rule..
0

One advice: Don't use CheckedExceptions! Always try to let your own Exception inherit from RuntimeException to let the user of your API the choice whether he likes to react to an exception or not!

Here is a blogpost which discribes the issue: http://jandiandme.blogspot.de/2013/05/why-javas-checked-exceptions-are-issue.html

EDIT: Would you please comment your downvote!

7 Comments

I didn't downvote, but I'm always wary of rules like "Don't use CheckedExceptions". The problem I have with UncheckedExceptions is that it makes it HARDER for the API user to react to an exception as, for the most part, they won't even know they will encounter it until the code runs and throws one. At least with CheckedExceptions the API user knows about the set of exceptions they have to handle at compile time. I agree that poorly defined APIs that throw a lot of checked exceptions can be painful to use, but we should encourage the developer to design better APIs, not hide its deficiencies
Don't use CheckedExceptions! - this depends, better is to say Prefer not using CheckedExceptions! :) (I didnt downvote too)
@DaveHowes You can also declare that your method throws an unchecked exception via the throws clause and in the JavaDoc. See no problem with that.
@MariuszS give me one example when a checked exception should be used.
@markusw - "You can also declare that your method throws unchecked ......". I agree - but who does this? Given that a lot of the article you refer to talks about developers handling CheckedExceptions badly, what makes you think that these same developers will put UncheckedExceptions in the method declaration?
|
0

@Narendra, Parent class in your API can extend Exception class, so that your API wraps checked and unchecked exception together. Or you can create new API extending RuntimeException to include un-checked exception. I will prefer first option for my implementation to reuse super references where ever required.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.