Chained Exceptions initCause(), is this correct? - java

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.

Related

How do I avoid getting "Missing return statement" when calling a method that throws an exception, from within another method?

I have a method that handles different error codes and always throws unchecked exception. This method is used in many places across the class. When I try to call it inside another method that has not void return type as shown below:
public Object someMethod() {
....
if(success){
return result;
} else {
callMethodThatAlwaysThrowsUncheckedExceptions();
}
}
java compiler says that the method is missing return statement.
Only two options come to my mind how to solve this problem:
replace method call with its content
add a return statement just after method call that returns an empty object
However I don't really like any of these options: the first one because of code duplication and the second one because of the need to write code that will never be executed.
Is there any other way to solve this problem?
Just swap around the terms, you'll never get to return if the method throws.
if(!success){
callMethodThatAlwaysThrowsUncheckedExceptions();
}
return result;
Or even
callMethodThatAlwaysThrowsUncheckedExceptions(succes);
return result;
Just check the success condition in your throwing method.
Next to the great answer already provided by Slawomir Chodnicki, here's another suggestion.
Change your callMethodThatAlwaysThrowsUncheckedExceptions() which somewhere throws an Exception into a factory method. E.g: change this:
// somewhere in callMethodThatAlwaysThrowsUncheckedExceptions
throw new MyException();
To:
return new MyException();
That way you can call that method like this:
throw callMethodThatAlwaysThrowsUncheckedExceptions();
And thus will help the compiler to see that this is the last statement of that execution branch.
This also works greatly with different exceptions, just return instead of throw
To indicate that you don't expect a line to be reachable (after your call to the throwing method) you can
throw new AssertionError("comment to your co-developers why this never gets reached")
I like minus's answer, but it can be a bit unreadable to users that might mistakenly think return result; will always be executed (regardless of the value of success).
As an alternative, you can change
void callMethodThatAlwaysThrowsUncheckedExceptions () {}
to
Object callMethodThatAlwaysThrowsUncheckedExceptions () {}
(no need to change the method body).
Now you can write
public Object someMethod() {
....
if (success) {
return result;
} else {
return callMethodThatAlwaysThrowsUncheckedExceptions();
}
}
None of the answers above matched my taste of programming. The closest match that I found is here. Inspired from this linked answer, I handled such missing return statement errors in the following way:
First making the return type of the method same as that of exception which it always throws
MyCustomRuntimeException callMethodThatAlwaysThrowsUncheckedExceptions() {
// ....
throw new MyCustomRuntimeException();
}
Next whenever we have to fail the method execution, simply call above method and throw it
public Object someMethod() {
// ....
if (success) {
return result;
} else {
throw callMethodThatAlwaysThrowsUncheckedExceptions();
}
}
This can be used even in methods having void return type without explicitly mentioning the throw keyword. Ofcourse in such places some IDEs may warn of UnusedReturnValue but that can be suppressed as well.

How to implement wrapper for multiple exceptions?

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.

How to handle errors properly

I'm a beginner in java writing an frontend for a webservice.I have to validate the input to get useful error messages for the user.Currently it works this way:
public Object zipVal(String zip)
{
try
{
if (zip.length() == 5)
{
val.setZip(Integer.parseInt(zip));
return val.getZip();
} else
{
return lengthError;
}
} catch (NumberFormatException e)
{
return formatError;
}
}
for zip Codes.Using Objects to declare the return type is not what I want tho(and is afaik discouraged),but I'm not sure how I should handle wrong inputs other than that.Should I just return null for every Exception and invalid input and handle such things in another method?
Edit:Added something to actually throw an Exception...
Yeah, exception handling might be one of the trickier things to consider (if one comes from a C programming background for example, where we used to be happy with < 0 return code for indicating erroneous program flow).
Normally you are pretty safe off by catching other API:s you integrate with and encapsulate them in your own exception (sort of masking them away), but by doing so don't forget to chain the original exception into your own with this constructor (and/or derivatives of such):
public MyException(final String message, final Throwable cause) {
super(message, cause);
}
One surely see alot of:
catch (Exception) {
return null;
}
and such in code as well, I wouldn't say that this is "good" object orientation, but it is still common and could be used in special occasions.
And also, its usually very important what you do (how to handle) when you catch the exception, someone told me that programing is 90% about error control and 10% about functionality :)
Here are some tutorials/resources:
http://docs.oracle.com/javase/tutorial/essential/exceptions/
http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/
If you are returning a value, then there is no need to handle the exception. It is better you declare that the method may throw the exception.
NumberFormatException is a RunTimeException. So if you wish to handle it, then better return an invalid zip (say -1) to let the caller know that something went wrong.
Otherwise, declare that you will throw a Custom Exception if NFE occurs.
This snippet may be useful.
public int setZipVal(String zip) // throws CustomException
{
try
{
if (zip.length() == 5)
{
val.setZip(Integer.parseInt(zip));
return val.getZip();
}
} catch (NumberFormatException e)
{
// Log the error and return invalid zip
return -1;
// OR throw custom exception
throw new CustomException("Length Error"));
}
}

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.

Categories

Resources