Is reclassing exceptions good practice? - java

Sometimes I reclass an exception like this:
try{
methodA(param1);
}catch(ExceptionType1 ex){
throw new ExceptionType2(ex);
}
An example of when I do this is when methodA's params should be safe and will not throw exceptions, so the ExceptionType1 is really indicative of a different problem (something like ExceptionType2).
This is not reclassing from checked exception to unchecked.

There's nothing wrong; in fact it's a commonly used pattern.
Rethrowing an exception wrapped in another exception is often used when the method contract throws a domain specific exception, but there's an implementation specific exception you must deal with, for example an SQLException.
public Customer getCustomer(int id) throws CustomerDataUnavailableException {
try {
// access SQL database
return customer;
} catch ( SQLException e) {
throw new CustomerDataUnavailableException(e);
}
}
The choice to store customer data in an SQL database is an implementation choice, which you don't want to leak out through the API (by throwing SQLException).
It also makes changing the implementation easy, for example using a flat file system on a mobile device, or using a NoSql db - the change can be made to the method without changing any other code, because the API contract is implementation independent.
Finally, it makes testing and mocking easier - you don't have to throw exotic exceptions, the classes of which may not even be accessible to your testing code.

It is OK - according to this URL, this is defined as a "chained exception" and it is legal:
http://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html
The following example shows how to use a chained exception.
try {
} catch (IOException e) {
throw new SampleException("Other IOException", e);
}
I would document the different types of exceptions using the #throws tag for JAVADOC. It is legal to include multiple #throws tags for one method; see this URL:
Can I use multiple #throws tags for the same exception in Javadoc?

Related

Is "throws Throwable" good practice

In the past I'd read tons of code with methods like:
public Object doSomething() throws Throwable {
...
}
Is it common practice to do that?
What are pros & cons?
throws Trowable seemed to me like the "Agent Orange" way of getting the Exception- matter done
EDIT
Handle expected Exceptions in the Method
Throw unexpected Exceptions (one by one)
Don't care of Errors
Is that the way to go?
You should not throw Throwable. Here's why.
Throwable is the top of the hierarchy of things that can be thrown and is made up of Exceptions and Errors. Since Errors by definition arise from unsalvagable conditions, it is pointless to include them in your method declaration. That leaves just Exception.
You should declare your method with throws Exception instead.
Note that the narrower the range of throws the better.
Declaring your method to be throws Exception is ok if your method doesn't generate the exceptions, but instead calls other code that is declared as throws Exception and you want exceptions to percolate up the call stack.
If your method is the generating the exception, then declare a narrower range, eg throws IOException, MyProcessingException, etc
That's a loaded question. This isn't so much about exception handling as it is about code readability.
It depends where you get your code samples from. Professionals prefer to be more specific when throwing out of a method. The main reason is that it keeps your APIs more readable. For example, if your method throws Throwable, that basically means anything could happen and your method doesn't want to deal with it, no matter what. But really, only a limited number of things could happen:
Whatever checked exceptions resulting from other calls you are making in your method
Whatever checked exceptions you are throwing on purpose based on your own assertions
Whatever unchecked exception you didn't plan for
Errors (java.lang.Error) that are more global to the JVM and the environment
By specifically stating the exceptions you want to throw, you are telling the users of your API about what they should beware of. For example, when you use InputStream, you'll notice most methods throw at least java.io.IOException, which gives you some useful information about what you should watch for.
When coding, as a general rule, you want to try to keep your APIs as expressive as possible. You've got essentially one line of code to show the public API of a method (i.e. its signature, annotations too I guess), so you want it completely expressive (return type, name, parameters, but also the thrown exceptions).
As far as catching the throwables and printing the stack trace, I'd say that you should not catch the exception unless you can do something about it. Instead, let it roll up the call stack until some class catches it to do something about it. Sometimes, it may roll all the way up to your main class, which I guess would have to catch it and print the stack trace as last resort. Basically, if you can't act upon the exception, then let it go up the call stack. Also it is extremely rare that you find yourself in a situation where you should silence an exception (i.e. catch it but do nothing about it). That's usually inviting problems when comes time to troubleshoot issues.
Here is a fun but interesting article around misuse of exception handling in general.
In some rare cases it is acceptable to throw Throwables. For example, #Around advices in Spring AOP are usually declared to throw a Throwable.
The following example is copied verbatim from Spring AOP docs:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
#Aspect
public class AroundExample {
#Around("com.xyz.myapp.SystemArchitecture.businessService()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
return retVal;
}
}
Why is doBasicProfiling declared to throw a Throwable? Because the original method (i.e. the execution join point), might throw an Error, RuntimeException, or a checked exception. So it only makes sense to declare doBasicProfiling to throw a Throwable.
Functionally, it is equivalent with throws Exception, since errors are unchecked.
I see no reason to declare a method to throw Throwable. However, this doesn't mean that catch and printStackTrace is a good alternative.
Usually, you want to catch throwables where you can do something sensible with them.
Code that throws a throwable you don't expect should explode gloriously, so you can see the error and fix the bug.
Is it common practice to do that?
In the JDK it is rare. This is mostly used when it is not clear how to handle checked exceptions.
What are pros & cons?
The pros is that you get your code to compile without worrying about checked exception.s
The cons is that exception you should be handling are being ignored.
Isn't it better to catch and printStackTrace()?
Unhandled exception are usually printed anyway so catching them doesn't help much.
You should catch an exception when you can add some value by doing so and add the exception to the throws clause when you can't.
It is really debatable matter.
Having method throwing too many exceptions will result in lot of error handling code. Some times it is not intended.
But because I don't like too many exception in signature does not mean that Lets use Parent of all exceptions and we are done!! It will not work.
What one can do is categorise exceptions such as BusinessException,ServiceException so that if you have a business rule which says that minimum balance in account can not be less than say 100$ then InsufficientBalance exception will be generated which will be child of BusinessException
so you method will be like
public Object doSomething() throws BusinessException {
if(!hasMinimumbalance())
{
throw new InsufficientBalance(ErrorCode);
}
}
What this will do is club related exceptions together and whenever API user wants to detect exception specific error then he can do it, else generic error handling is possible.
The core point here is on the UI you should display to the user that You have run out of balance and you can not withdraw money
You can say on the larger aspect to display human readable form of error it is really necessary to have separation of exceptions.
Are you asking about Throwable specifically? If so, then it's not good practice. It doesn't provide any useful information to class (method) user.
Throwing (and catching) Throwable (or Exception) is generally bad practice because it 'blankets' any specific exceptions you might want to catch. Then you would have to resort to ugliness like below:
public void myMethod() throws Throwable {
if (x) {
throw new MyException1();
}
if (y) {
throw new MyException2();
}
}
public void callingMethod() {
try {
myMethod();
}
catch(Throwable t) {
if (t instanceof MyException1) {
// handle exception 1
}
else if (t instanceof MyException2) {
// handle exception 2
}
else {
// handle other exceptions
}
}
}
Which is error prone (and flagged by CheckStyle as a code violation). It is much preferrable to have code like this:
public void myMethod() throws MyException1, MyException2 {
if (x) {
throw new MyException1();
}
if (y) {
throw new MyException2();
}
}
public void callingMethod() {
try {
myMethod();
}
catch(MyException1 e) {
// handle exception 1
}
catch(MyException2 e) {
// handle exception 2
}
}
Handling an exception just by calling printStackTrace() is usually not a good idea. printStackTrace() sends the stacktrace to standard error, which may not be read at all. A better option is to use the application's logging facility (like log4j) to report the exception. Even then, just logging it might no be enough.
My rule of thumb is:
If you can handle an exception locally, do so. For example when parsing a String as an Integer you could catch the NumberFormatException and return a default value:
prvate int parseAmount(String amountValue) {
int amount;
try {
amount = Integer.parseInt(amountValue);
}
catch(NumberFormatException e) {
// default amount
amount = 0;
}
return amount;
}
If you cannot handle an exception locally, consider if you should expose the exception type that is being thrown. If this type is some obscure (implementation-dependent) type, then wrapping it in your own generic exception type is probably a good idea:
private Customer getCustomer(int customerId) throws ServiceException {
try {
return customerService.getCustomer(customerId);
}
catch(CustomerServiceSpaghettiTangledException e) {
throw new ServiceException("Error calling the customer service", e);
}
}
Here 'ServiceException' is a subclass of Exception created by you. Spring also offers an exception hierarchy specifically for this purpose.
By wrapping the exception you hide the implementation details, making your service layer much simpler to use.
If you decide to throw an exception from your method, you will need to handle it 'higher up' in the callstack. This can be a generic error page in your web application stating that something went wrong and possibly providing an error message or code. In some cases the higher level code can attempt a retry or possibly an alternative way to obtain the required result.
The only use case I can think of would be for test code like unit tests. But Adam's counterpoint still stands "If so, then it's not good practice. It doesn't provide any useful information to class (method) user."

Should I create a custom exception type so my code is easier to unit test

In my unit test, I test a method for an expected RuntimeException and I want to distinct those thrown by my component from ones thrown by the code called in the method.
Creating a custom exception type is unnecessary and does not solve the problem if the method throws the same exception type but for different reasons, e.g. InvalidArgumentException.
Looks like the only way to tell them is the message or the error code. Because the message can be changed during development, the error code seems the only reliable option.
What is the best practice for creating of system of error codes so they don't conflict with ones of external packages, eg. third party libraries?
Creating a custom exception type is unnecessary and does not solve the
problem if the method throws the same exception type but for different
reasons, e.g. InvalidArgumentException.
Why do you think it's unnecessary? This is what you should do. Derive your own custom exception classes, throw their instances from your code and catch them outside (in your unit tests). The catch statement can be repeated in anticipation of multiple different exception classes:
try {
// something
} catch (MySpecificException e) {
// you know that your code threw this
} catch (Exception e) {
// this is coming from somewhere else
}
--Edit--
Sorry, I didn't see the java tag. Even though the following example uses PHP constructs, the principles should still apply.
--Original--
I use custom exception codes in only a few, very specific cases, and I store these codes in a custom exception class which extends the default exception class. They are stored in the class as constants, as the value doesn't really matter, but the context does.
Consider:
class CoreLib_Api_Exception extends Exception
{
const EXCEPTION_FORMAT = '%s (%s): %s';
const CODE_FILE_DNE = 100;
const CODE_DIR_BASE_EQUALS_REMOVE = 101;
const CODE_XML_READER_UNABLE_TO_OPEN = 200;
const CODE_XML_READER_UNABLE_TO_READ = 201;
}
// Example usage
class CoreLib_Api_Reader
{
protected function getReader()
{
$reader = new CoreLib_Api_Xml_Reader();
if (!#$reader->open($this->getFileUri())) {
$e = new CoreLib_Api_Exception(sprintf('Could not open %s for parsing', $this->getFileUri()), CoreLib_Api_Exception::CODE_XML_READER_UNABLE_TO_OPEN);
throw $e;
}
}
}
// Calling code
try {
$reader = CoreLib_Api_Reader();
$reader->setFileUri($fileUri);
$reader->getReader();
} catch (Exception $e) {
// If code is anything other than open, throw it
if ($e->getCode() !== CoreLib_Api_Exception::CODE_XML_READER_UNABLE_TO_OPEN) {
throw $e;
}
$e = null;
$reader = null;
}
By using the exception code, I can check to determine if the reader is unable to open the file, if so ignore the exception and move on, otherwise throw the exception and break the flow.
And if one of my exception codes collides with a third party exception code, it doesn't matter, as I mentioned before, using constants, the context will dictate which code I want to match on.
I test a method for an expected RuntimeException
I think this is a mistake. A RuntimeException should be used only for indicating bugs in the code that the code itself can detect. Testing should test only for specified (defined) behaviour. But when there is a bug in some code, its behaviour is undefined (who knows where the bug could be or what it might do). So there is no point in trying to specify what RuntimeExceptions some code should throw; that is like specifying how the code should behave "in the presence of a bug". Throwing particular RuntimeExceptions with particular messages should be seen as a courtesy to the maintenance programmer (who is likely to be you).

Huge exception handling blocks in Java

At the moment i working with library which can throw hell alot of different exceptions(8-10 per method call) and most of them must be handled, worse of all every method (at any time) can throw AuthenticationExpiredException, and i must re-attempt to authenticate. For example:
try {
xStream = xSet.createXStream(id, binding, mimeType); //Method call
} catch (AuthenticationExpiredException authenticationExpiredException) {
try {
this.authenticate(); // re-authenticate
xStream = xSet.createXStream(id, binding, mimeType); //Method call again
} catch (XAMException xamException) {
throw new ConnectorException(
"Error occurred during creating new Blob after attempting to re-authenticate",
xamException);
}
} catch (XSystemCorruptException xSystemCorruptException) {
this.entities.clear();
this.closeConnection();
throw new ConnectorException("XSystem was corrupt and connection was closed",
xSystemCorruptException);
} catch (XSetCorruptException xSetCorruptException) {
this.closeEntity(entity);
throw new ConnectorException("XSet for entity: " + entity.getXuid()
+ " was currupt and removed", xSetCorruptException);
} catch (XAMException xamException) {
throw new ConnectorException(
"Error occurred during creating new Blob.", xamException);
}
And this is one of the smallest examples of exception handling. The main question here, is there any way to reduce amount of code which handle exceptions, and make logic cleaner?
UPDATE
Thanks for your feedback. I decided to create separate wrapper for this library by wrapping every method and handling them respectively. To support different handling methods i created interface for wrapper and then implemented it with my custom wrapper like this:
public interface XAMLibraryWrapper{
// Methods
}
/**
* Will attempt to recover before throwing RuntimeException
*/
public class RecoveringXAMLibraryWrapper implements XAMLibraryWrapper{
// Implementation
}
If there is a consistent way to handle those method (i.e. you always wrap them in the same way and re-throw a RuntimeException, then a custom wrapper library might be the appropriate approach. This can still work when there are 2-3 different ways to handle them (by providing 2-3 wrapper methods (or even classes) for a single wrapped method/class).
Alternatively, if two or more exception types have the exact same handling code, then you can try to look for Java 7 to get multi-catch.
You can use Template method pattern. JdbcTemplate is a wonderful example how this design pattern can simplify exception-heavy code (SQLExceptions in this case).
If the API is indeed designed to throw that many exceptions, and each of them requires different handling, then there isn't much you can do.
One thing you can do is move repeated code in a separate method, or use Java 7 multi-catch.
If you have different things to do for each exception I'm afraid all those catch statements might be necessary. However, if you have lot's of catch statements with the same content or lot's of resources to close, you might have a look into the new Java 7 features like multiple exceptions in one catch and automatic resource handling. I'm not sure Java 7 is an option for you though.

Which exception should I throw when building cache fail?

I have a class that contains a cache (Set), and the cache is built on instantiation. I'm confused which exception/error should I throw if building cache fail (cannot connect to database or some).
class Provider {
public Provider() {
buildCache();
}
private void buildCache() {
try {
this.cache = getDataFromDb();
} catch (Exception ex) {
throw new ???
}
}
}
One exception comes in my mind is ExceptionInInitializerError, but javadoc says it is thrown on initialize static members.
Should I throw an IllegalStateException cause the cache isn't built so this class is useless?
Clearly I can create my own ErrorOnBuildingCache and throw it but I wonder if any exception in Java library suits this circumstance.
If you're in doubt as to which exception should be thrown, then so will users of your code. So define your own exception type (e.g. FailedToInitializeCacheException) and throw that. No ambiguity that way.
IllegalStateException would be a reasonable fallback position, but you should never, ever use ExceptionInInitializerError (or anything ending in Error) - that's low-level classloader stuff, don't mess with that.
Clearly I can create my own
ErrorOnBuildingCache and throw it but
I wonder if any exception in Java
library suits this circumstance.
This is exactly what you should do. Do not try to use an existing exception, but instead make one of your own. So you know when it is throwed that it is related to your cache and not a static field instanciation error or something.
On a side note, you shouldn't catch exception excepted in very specific cases. Catching exception will catch everything like null pointer exceptions, divide by zero, IO errors, security exception.
What I would do is:
Include the cause when rethrowing the
exception to allow better
investigation
Catch exceptions that could occurs
due to IO/Network problems but
associate them with the right error
message. In you case this is DB exceptions.
Do not catch exception that are due
to programming bugs (like null
pointers), let them popup so you
directly know the real error cause.

Changing the type of Exception a method throws in Java

What I am trying to do feels counter intuitive, but Java keeps surprising me all the time, so I give it a shot.
I am implementing an application with the help of the ESAPI library. This library provides its own exceptions. In addition to the well known exception behavior those exceptions do things like automatic logging with log4j and providing information to an intrusion detection module.
Now I want to use these features in all parts of my application. Anytime a method of mine throws an exception, I don't throw a normal exception but a selfmade exception that extends from the new EnterpriseSecurityException. Works like a charm.
But what can I do if I use a method, that throws a normal exception? Let's say I want to read a file using an java.io.FileInputStream? It cannot find the file and throws a FileNotFoundException. Unfortunately the FileNotFoundException does not provide the features of my own Exceptions, because it does not extend the EnterpriseSecurityException.
Is there any trick in Java to change the exceptions a method throws? It sounds strange to me as I write this, but maybe someone can come up with a solution. The only idea I had so far is catching the normal exception, extract the relevant information, and build a new exception with it. But this seems pretty crude...
Catch the exception and throw a new one that extends from EnterpriseSecurityException and pass the old exception to the new one to chain them together.
try {
...
} catch (FileNotFoundException e) {
throw new CustomEnterpriseSecurityException(e);
}
By chaining the exceptions you won't lose the stack trace from the original exception.
You can do this. Just catch the original exception and throw an appropriate exception you defined yourself and which extends EnterpriseSecurityException. Ensure that you chain the exceptions so that the stacktrace does not get lost.
For example with your file open example:
try {
//open file
} catch (FileNotFoundException e) {
throw new YoureCustomException("This is your message", e);
}
May be you can do like this:
try{
// file operations
}catch(FileNotFoundException e){
throw new MyCustomeFileNotFoundException(e);
}
Create your exception version for predefined exceptions and when you get any predefined exception in catch throw your defined exception.
A technique I've found very useful is to chain exceptions by using the Exception(Throwable cause) constructor as the superclass constructor. That way, you don't lose any of the stack trace, but can provide custom handling in your own class (which can look at the cause with the getCause() method if it wishes). For instance:
try{
//do something
}
catch(FileNotFoundException e){
throw new MyFileNotFoundException(e);
}

Categories

Resources