How to implement wrapper for multiple exceptions? - java

I've some modules, each containing some models what I want to parse from persisted file(s).
When I read a file I don't know which module will be able to parse it, that's why I try to parse it with my first module's parser. If that fails I try with the parser of the second module and continue that until I've tried all my parsers.
The parsers can give back information in form of multiple exceptions (different subtypes of Exception class) or the parsed model object (different subtypes of a ModelBase class).
If none of the parsers succeed I want to wrap all of given exceptions into one big Exception, throw it and catch it somewhere in my application code (in form of a new big exception), where I can handle the problem (e.g. show all the parsing problems and stacktraces to the user, handle them somehow etc.).
My pseudocode:
ModelBase getModelOrBigException(File file)
throws MyBigException {
List<Exception> exceptions = new ArrayList<>();
for (Module module : myModules){
try {
ModelBase model = module.parse(file);
return model;
}
catch (ParsingException1 p1) { exceptions.add(p1); }
catch (ParsingException2 p2) { exceptions.add(p2); }
}
throw new MyBigException(exceptions);
}
I want to call the code
void openFilesHandler(){
//... selecting file
try {
process(getModelOrBigException(file));
} catch (MyBigException e) {
// process the sub-exceptions or show them to user or print stacktraces of all sub-exceptions or show sub-exceptions by type etc
}
}
Obviously if I catch MyBigException I won't be able to call methods like getStackTrace(), getMessage(), getLocalizedMessage() on them by default, only if I implement my exception class similar to this:
class MyBigException extends Exception {
public MyBigException(Exception e1, Exception e2, ..., Exception eN){
super(e1, e2, ..., eN); // This is not possible, only one argument is acceptable
}
}
or to this:
class MyBigException extends Exception {
List<Exception> exceptions = new ArrayList<>();
public MyBigException(List<Exception> exceptions){
super(exceptions); // This is not possible, list or array of exceptions is not allowed here
}
}
Questions:
How should I create a new type of Exception, which can store multiple exceptions with support of the original Exception class's methods?
When I do this:
myBigException.printStackTrace();
or this:
myBigException.getMessage();
I want to print/get all stacktraces of all stored exceptions.
Should I pass all given exceptions to super() method?
Is there any better way to do the parsing solution better than the solution above?

I want to print/get all stacktraces of all stored exceptions. Should I
pass all given exceptions to super() method?
If you wanted to print all stacktraces or exception messages, you are almost there and you need add few more bits as explained below:
(1) Inside MyBigException, create a constructor MyBigException(List<Exception> exceptions, String exeptionMessage) and call super(exeptionMessage);
(2) override printStackTrace() in your MyBigException and iterateover the List<Exception> and call printStackTrace() on each exception object.
You can refer the below code on the same:
MyBigException class:
public class MyBigException extends Exception {
private List<Exception> exceptions = new ArrayList<>();
public MyBigException(List<Exception> exceptions, String exeptionMessages){
//call super and pass message
super(exeptionMessages);
this.exceptions = exceptions;
}
public void printStackTrace() {
for(Exception exception : exceptions) {
exception.printStackTrace();
}
}
}
getModelOrBigException() code:
ModelBase getModelOrBigException(File file)
throws MyBigException {
List<Exception> exceptions = new ArrayList<>();
//Capture exception messages as well using StringBuilder
StringBuilder exceptioMessages = new StringBuilder();
for (Module module : myModules){
try {
ModelBase model = module.parse(file);
return model;
}
catch (ParsingException1 p1) {
exceptions.add(p1);
exceptioMessages.append("YOUR MESSAGE FOR ParsingException1;");
}
catch (ParsingException2 p2) {
exceptions.add(p2);
exceptioMessages.append("YOUR MESSAGE FOR ParsingException2;");
}
}
throw new MyBigException(exceptions, exceptioMessages.toString());
}

Two options come to my mind.
suppressing the given exceptions using addSuppressed. You can then retrieve it again later using getSuppressed(). This is also the mechanism which is used on try-with-resources-statements throwing exceptions. This way the stack trace of your myBigException also shows the suppressed ones automatically.
add an accessor method to your exception classes internal list so you can access it from outside, e.g. getExceptions(). Here however you need to handle the stack trace of each exception yourself. You can overwrite the printStackTrace(*) methods, but that seems overhead to me.
It mainly depends on what you want to achieve (or what is more appropriate) and how you want to access the exceptions later on.
You may also want to supply your own printStackTraces() method in the second case or overwrite the getMessage()-method in both cases to supply a message that is more appropriate.

You can't have many exceptions as the cause of your BigException. One exception is thrown and it goes up the stack until you handle it. You could add it to a causality relation chain, and that's why Exception's constructor accepts another exception as the cause of this exception.
But in your case, you are throwing the BigException after many parsing exceptions have been thrown and already handled (by adding them to a list).
So your first exception in the chain is actually BigException. If I were you, I would just have a getter for the list of parsing exceptions and work with that list, i.e. to inform the user, log the list etc.

Related

Where to check for values and throw an exception

Let's say I have a class like the following one:
public class Parameter {
private double[] parameterValues;
public Parameter(double[] parameterValues) throws BadElementInitializationException {
checkParameterValues(parameterValues);
this.parameterValues = parameterValues;
}
public double[] getParameterValues() {
return parameterValues;
}
public void setParameterValues(double[] parameterValues) throws BadElementInitializationException {
checkParameterValues(parameterValues);
this.parameterValues = parameterValues;
}
private void checkParameterValues(double[] parameterValues) throws BadElementInitializationException {
if(parameterValues == null)
throw new BadElementInitializationException("Parameter values cannot be null");
if(parameterValues.length == 0)
throw new BadElementInitializationException("Parameter values cannot be empty");
}
public int noOfValues(){
return parameterValues.length;
}
}
And the array is later used to perform some calculations.
My question is, where should I check that parameterValues is not null, nor empty? Should I do that in the Parameter class, like I did, or should I do that in the class which performs calculations?
Moreover, should I throw an exception here, or in the Calculation class? And what would be the reason to throw checked and what to throw unchecked exception? My goal is to make a stable application that won't crash easily.
You should do it in all places where getting an null or empty array is not valid. If you do it just in your Parameter class and rely on this having done the check in your Calculator class, then what if you start to use your Calculator class somewhere else? Who are you going to rely on to do the checks there? If you do it in the Calculator class and then refactor the Parameters class to use something else in the future, then your check will go away.
If its also invalid to have a null or empty array in your Calculator class then you need to check there as well.
Alternatively pass an object to both which cannot be empty and then you only need to make the null check.
Should I do that in the Parameter class, like I did, or should I do
that in the class which performs calculations?
In my opinion, better to check in Parameter class then any other classes. You could see how it do in google guava , for example, in most class they use:
public static boolean isPowerOfTwo(BigInteger x) {
checkNotNull(x);
return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}
or
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
...
Moreover, should I throw an exception here, or in the Calculation
class?
If you check your parameters in Parameter class, better throw in Parameter class also. In addition to, you may use some standart function to check and throw exception, for example from google guava:
com.google.common.base.Preconditions.checkNotNull
com.google.common.base.Preconditions.checkArgument
com.google.common.math.MathPreconditions.checkPositive
And what would be the reason to throw checked and what to throw
unchecked exception?
A checked exception is good if you think that you must catch and working this exception later. In most case, for wrong parameters quite enough unchecked exception, like standart IllegalArgumentException in Java. Also, a checked exception need to say other programmers (who use this API) that this exception could be happened, and they need to working with it. Working with an unchecked exception is quite easy for programmer (and often reduce your source code), however a checked exception become your code is more reliable.
A more info about checked and uncheked exceptions, you could find in this post

Chained Exceptions initCause(), is this correct?

I have a method:
public void SomeDataMethod() throws BadDataException {
try {
// do something
} catch(IOException e) {
throw new BadDataException("Bad data",e);
} finally {
// do something regardless of above
}
}
And now for example some code will invoke this method, and I want to see all failures which happened in this method,
so how can I do it by using initCause()? Or maybe is there any other way to do this? And if I use initCause():
1) will I get all exceptions which were catch or the last one?
2) and What form do I get them / it?**
When you call an Excepion Constructor with the throwable attached, like you have the e as part of the new BadDataException("Bad data",e); then the result is effectively the same as:
BadDataException bde = new BadDataException("Bad data");
bde.initCause(e);
This is to keep compatibility with earlier Java versions which did not have the initCause concept.
Not all exceptions support adding the cause as part of the constructor, and for those exceptions you can initCause it.
note that you can only initCause an exception once, and initializing it with 'null' cannot later be changed:
BadDataException bde = new BadDataException("Bad data", null);
// this will fail.....
bde.initCause(e);
To get the cause of an exception, you call... getCause(). In this case, this method will return the IOException that you wrapped inside your BadDataException. It can't return more that one exception, since you can only wrap one exception.

Handling a new exception in an anonymous inner class

I have a situation similar to the following:
/** Get a list of records */
public ArrayList<Record> foo() throws BazException{
// Create the list
static ArrayList<Record> records = new ArrayList<Record>();
// Use MyLibrary to load a list of records from the file
String str = SomeoneElsesLibrary.loadData(new File("mydata.dat"), new DataLoader(){
// will be called once for each record in the file
String processRecord(Record r){
// if there's no "bar", invalid record
if( ! r.hasField("bar") ){
throw new BazException();
}
records.add(r);
}
});
return records;
}
Obviously this doesn't work, because SomeoneElsesLibrary has no idea what a BazException is. I also can't say processRecord() throws BazException because then the prototype would no longer match. I'm starting to think that my overall structure for this implementation is wrong. (I'm recovering from a bout of Node.JS addiction and have to re-learn some most Java patterns.) How would I restructure my code to make it more idiomatic Java?
Pseudocode is fine, or even just a description. Also, don't feel like you need to use an anonymous inner class, like I did in my first go at it; I'm just looking for "the Java way" to do this.
Ryan, ensure that your BazException is an extension of the RuntimeException (unchecked exception) rather than Exception (checked one).
Otherwise, as you must have probably noticed, the compiler will complain about not handling your own exception.
For more information, have a look to some information about unchecked exceptions (i.e. RuntimeException or Error):
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
An exception refers to the method can throw it, not to a class (SomeoneElsesLibrary).
There are two types of exceptions, checked (subtype of Exception) and unchecked (subtype of RuntimeException). The checked must be declared explicitly in the signature of the method that can throw it. The unchecked can propagate without being declared in the signature of the method and without being handled by no try/catch block.
Generally checked are used when the caller of the method that raises the exception can remedy it, the unchecked otherwise.
You can handle the unchecked exception in foo() method by a try/catch ...
public ArrayList<Record> foo(){
static ArrayList<Record> records = new ArrayList<Record>();
try{
SomeoneElsesLibrary.loadData( ... );
} catch (BazException be){ // you just handle the exception here
}
return records;
}
... or not
public ArrayList<Record> foo(){
static ArrayList<Record> records = new ArrayList<Record>();
// if SomeoneElsesLibrary.loadData raise the BazException
// it is propagated to the caller of foo()
SomeoneElsesLibrary.loadData( ... );
return records;
}
Instead a checked exception must always be handled.

Better way for DB exception handling in java

Which one will be better: ErrorCode or Exception for that situation?
I have ever been seeing these two error handling techniques. I don't know the disadvantages and advantages for each technique.
public void doOperation(Data data) throws MyException {
try {
// do DB operation
} catch (SQLException e) {
/* It can be ChildRecordFoundException, ParentRecordNotFoundException
* NullValueFoundException, DuplicateException, etc..
*/
throw translateException(e);
}
}
or
public void doOperation(Data data) throws MyException {
try {
// do DB operation
} catch (SQLException e) {
/* It can be "CHILD_RECORD_FOUND, "PARENT_RECORD_NOT_FOUND"
* "NULL_VALUE_FOUND", "DUPLICATE_VALUE_FOUND", etc..
*/
String errorCode = getErrorCode(e);
MyException exc = new MyException();
exc.setErrorCode(errorCode);
throw exc;
}
}
For second method, the error code retrieve form configuration file. We can add Error Code based on the SQL Vender Code.
SQL_ERROR_CODE.properties
#MySQL Database
1062=DUPLICATE_KEY_FOUND
1216=CHILD_RECORD_FOUND
1217=PARENT_RECORD_NOT_FOUND
1048=NULL_VALUE_FOUND
1205=RECORD_HAS_BEEN_LOCKED
Caller client for method 1
try {
} catch(MyException e) {
if(e instanceof ChildRecordFoundException) {
showMessage(...);
} else if(e instanceof ParentRecordNotFoundException) {
showMessage(...);
} else if(e instanceof NullValueFoundException) {
showMessage(...);
} else if(e instanceof DuplicateException) {
showMessage(...);
}
}
Caller client for method 2
try {
} catch(MyException e) {
if(e.getErrorCode().equals("CHILD_RECORD_FOUND")) {
showMessage(...);
} else if(e.getErrorCode().equals("PARENT_RECORD_NOT_FOUND") {
showMessage(...);
} else if(e.getErrorCode().equals("NULL_VALUE_FOUND") {
showMessage(...);
} else if(e.getErrorCode().equals("DUPLICATE_VALUE_FOUND") {
showMessage(...);
}
}
I recommend using Spring's JDBCTemplate. It will translate most existing databases' exceptions into unchecked exceptions that are specific, e.g. DataIntegrityViolationException. It will also include the original SQL error in the message.
Strange question, since both approaches do the same thing: they transform a checked SqlException in a different exception which seems to be unchecked. So the first one is the better one because it moves this into a single method.
Both leave some questions to be asked:
Isn't there some infrastructure that can do this conversion (Spring Template was mentioned in another answer)
Do you really want checked Exceptions, in my mind they are hardly ever worth the trouble.
Who is doing the real handling of the exception, does it get all the information needed? I would normaly expect some additional information about the transaction that failed inside of MyException, like: What did we try to do? (e.g. update a busines object); On what kind of object? (e.g. a Person); How can we/the user Identify the object (e.g. person.id + person.lastname + person.firstname). You will need this kind of information if you want to produce log/error message that tell you or your user more than 'Oops, something is wrong'
Why is MyException mutable (at least in the 2nd example)
A better design than either one would be to make your custom exceptions unchecked by extending RuntimeException.
I'd want your exception to wrap the first one, so coding it this way would be better, too:
MyException exception = new MyException(e); // wrap it.
If you do that, the second one is preferred. More information is better.
IMHO, it depends as how tightly your code is coupled with SQL.
If the method is to always (*1) be coupled with SQL, I would just declare and rethrow the SQLException (after cleanup / closing resources). Upper methods that are SQL-aware would then process it as they see fit (perhaps they need all the detail, perhaps they not).
If sometime in the future you could change the method for another which does not use SQL, then I would go for the second option.
(1): Be extra pessimistic with this assumption: "I think we are not going to change" should be interpreted as "Probably we will want to change". "We are not going to change" means "We cannot change without breaking lots of other methods anyway".
One differnce would the way you will catch the exception. In the first cases you can just catch the exception and you know what the error is. In the second case you have to catch the exception and check the code to see what the error is.

Checked and Unchecked Exceptions and design thoughts

Lets say have this immutable record type:
public class Record
{
public Record(int x, int y) {
Validator.ValidateX(x);
Validator.ValidateY(y);
X=x;
Y=y;
}
public final int X;
public final int Y;
public static class Validator {
public void ValidateX(int x) { if(x < 0) { throw new UnCheckedException; } }
public void ValidateY(int y) { if(y < 0) { throw new UnCheckedException; } }
}
}
Notice it throws an unchecked exception. The reason is because this is a object that is used quite often and it is inconvenient to have to deal with a checked exception.
However, if this object is in a class library where it may be used to validate user inputs (or some other external input). Now it's starting to sound like it should be a CHECKED exception, because the inputs are no longer up the to programmer.
Thoughts everyone? should i make checked or unchecked, or are there better design for this?
UPDATE:
my confusion is coming from this scenerio: normally Record would be used like this:
Record r = new Record(1,2);
OtherObj o = new OtherObj(r);
there it's up to the programmer, so unchecked exception is ok.
However when you get parameters for Record from a user you want to validate them right? so you might call
Record.ValidateX(inputX);
Record.ValidateY(inputY);
There it might throw a checked exception because inputs are no longer controlled?
Sorry, I normally wouldn't be too concerned with this (personally I think unchecked is fine). but this is actually a problem in a homework and I want to get it right lol.
UPDATE(2):
I starting to think what I need is for ValidateX to throw a checked exception because it is typically what would be used if user input is involved. In that case we could ask the user for input again. However, for the Record constructor, it will throw checked exception because constructing a Record with invalid arguements is an API violation. The new code would look like this:
public class Record
{
public Record(int x, int y) {
try
{
Validator.ValidateX(x);
Validator.ValidateY(y);
}catch(CheckedException xcpt) { throw new UnCheckedException(xcpt.getMessage()); }
X=x;
Y=y;
}
public final int X;
public final int Y;
public static class Validator {
public void ValidateX(int x) throws CheckedException { if(x < 0) { throw new CheckedException; } }
public void ValidateY(int y) throws CheckedException { if(y < 0) { throw new CheckedException; } }
}
}
Now the programmer can validate the parameters before passing them to the Record class. If the does not then it's a API violation and an unchecked exception is thrown.
How does this sound?!
Notice it throws an unchecked
exception. The reason is because this
is a object that is used quite often
and it is inconvenient to have to deal
with a checked exception.
No, I think the reason you throw an unchecked exception here is because it involves a violation of contract on the part of the user of that API, and not an exceptional condition during the normal functioning of that method. See the Java SDK's use of NullPointerException, IllegalArgumentException, etc., which are RuntimeExceptions because they represent a violation of contract.
Bloch, item 58: Use checked exceptions
for recoverable conditions and runtime
exceptions for programming errors.
If the user of your class is able to avoid the problem by using the API correctly (including not passing in values that are documented to be invalid) then it's a programming error, so throw an InvalidArgumentException.
You should never validate user input with an unchecked exception. Exceptions are normally checked because that way you can not forget to handle the exceptions.
Validating parameters used in an api is a completely different kind. These should be unchecked, because otherwise you'll end up adding try/catch to every function call. Whenever a method is passed an invalid argument, this is surely a programming error. The normal way is to throw an IllegalArgumentException or NullPointerException (or any other that suits your needs).
In api calls leave the checked excpetions for
Validations you promise to the caller of the api
Expected exceptional conditions (requested file doesn't exist, write failed etc)
Besides the above, recoverability is also important for deciding for a checked or unchecked exception. If you can never recover (which is normally the case in a programming error) you can (or should?) take the unchecked exception.
Preferably don't write code that doesn't meet the above guidelines. For you that would mean that you have to write a function that returns a boolean or checked exception when using to validate user input, and an unchecked exception when validating input parameters to your functions. Of course your can and should use the same function to validate the exceptions, just wrap the one that returns a boolean or checked exception:
public boolean validateX(int x)
{
return x > 0;
}
private void validateParameter(int x)
{
if (validateX(x))
{
throw new IllegalArgumentException("X is invalid");
}
}
This is a bit more work, but it will give you the best of both worlds. By making the validate parameter function private you can ensure you don't accidentally use it outside of your class. Of course you can also put the if(validateX(x)) ... part inside your constructor.
Really, it's all about expectations. If you expect that under normal program flow an invalid input may be entered, it should be a checked exception so you can recover gracefully. Unchecked exceptions are for error cases that the programmer can't do anything about and doesn't expect to happen normally.
If this is really meant to be for a validator class, then I would expect it to be unusually flexible on its range of allowable input, simply because it's purpose for existence is to test validity, which it can't do nicely by throwing exceptions.
public interface Validator<T> {
public boolean isValid(T object);
}
public final class PositiveIntegerValidator implements Validator<Integer> {
public boolean isValid(Integer object) {
return object != null && object > 0;
}
}
As a rule of thumb I always handle exceptions at the public interface to my component/layer/api. This allows exceptions to bubble up and be handled at the top level - Last Responsible Moment, whilst ensuring I handle the exception in my code, avoiding leaky exceptions.
BTW Some excellent advice regarding database exceptions on this question and general exception handling on this question

Categories

Resources