Handling a new exception in an anonymous inner class - java

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.

Related

Is there a short elegant way to write variable providing with exception?

So, I want to write these kind of things for my code, but there's too much code for one variable. How can I use modern Java for solving this problem shorter or cleaner? Moving it in the separate method doesn't solve the problem, because I still need to check the variable for null, which is wordy and adds extra method that used only once. It is possible to use Optionals here? Seems like return prevents this. Maybe there's the way for collapsing this thing into one for many variables like the foo described below? I don't know, just something to make it more readable and clean.
Foo foo;
try {
foo = FooProvider.getFoo(...);
} catch (FooProvidingException e) {
System.err.println("Foo exception: " + e.getMessage());
return;
}
// use foo, maybe in another method (when foo is the field).
I know, this question may be opinionated, but any help would be a valid answer.
Sorry for my poor english and thanks in advance!
What you're asking is not very clear, so I don't know at which extent my answer will be meaningful.
If I understand well, you have fields of any type (Foo, Bar...) and you would like to instantiate them using whatever kind of provider you wish, which can throw an exception while providing.
So at first, I don't think that you should return if an exception is thrown by the provider, but rather re-throw it or handle it. Because if you had an exception while getting your Foo and so you actually don't have a Foo, why would you continue (or why wouldn't you try to handle it somehow)?
Now this said and assuming that re-throwing/handling is taken care of, then I would define a ThrowingSupplier functional interface:
#FunctionalInterface
public interface ThrowingSupplier<T, E extends Exception> {
T get() throws E;
}
... and then I would create a static method like this:
public static <T, E extends Exception> T provide(ThrowingSupplier<T, E> supplier) {
try {
return supplier.get();
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
throw (E) e;
}
}
So at that point, I would be simply calling this utility method every time that I want to execute such kind of operation:
Foo foo = provide(() -> FooProvider.getFoo(...)); //either creates a Foo, or prints and re-throw a FooProvidingException
Bar bar = provide(() -> BarProvider.getBar(...)); //either createa a Bar, or prints and re-throw a BarProvidingException
Integer myInt = provide(() -> 3);
String myStr = provide(() -> "hello");
//... and so on
But of course, at least once you'll have to extract the logic. Then it's all about extracting it in a way that it becomes generic and doesn't need to be repeated for each distinct type of object.
I am also not sure what the end-goal here is but, as I understand it, here's a simpler version of achieving the following:
Declaring and initializing the variable(s)
Fetching values for it with a service provider
Handling any exceptions thrown by this (or if the value is null) and exiting method
Continuing execution if everything is as expected
public static void main(String[] args) {
Foo foo1, foo2, foo3, foo4;
try {
foo1 = Optional.ofNullable(FooProvider.getFoo()).orElseThrow(new FooProviderException(1));
foo2 = Optional.ofNullable(FooProvider.getFoo()).orElseThrow(new FooProviderException(2));
foo3 = Optional.ofNullable(FooProvider.getFoo()).orElseThrow(new FooProviderException(3));
foo4 = Optional.ofNullable(FooProvider.getFoo()).orElseThrow(new FooProviderException(4));
// this works in or out of try/catch block
foo1.printName();
foo2.printName();
foo3.printName();
foo4.printName();
} catch (FooProviderException fpe) {
System.out.println("Exception: " + fpe);
return;
}
// this works in or out of try/catch block
foo1.printAgain();
foo2.printAgain();
foo3.printAgain();
foo4.printAgain();
}

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.

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

Java - How to exit a method without return what he is expecting?

I've a method similar to the one bellow, where I want to return a private variable of one class only and only if, some conditions are verified. Otherwise I want to exit the method without return anything. I've tried something like the code bellow but I'm afraid that returning null is not a good idea. Are there any way to exit a method like the break keyword works for cycles?
private Classxpto classxpto;
public Classxpto getclassxpto(String abc, Date asd){
String curr_abc= classxpto.getabc();
Date curr_asd= classxpto.getasd();
if("my conditions"){
//dont return classxpto
return null;
}else if("my other conditions"){
classxpto.setabc(abc);
classxpto.setasd(asd);
return classxpto;
}
return null;
}
You can either return null (or some default Classxpto instance) or throw an exception. Throwing an exception is the only way to exit a method having a non-void return type without returning anything.
You cannot return "nothing" from a method unless it is declared as a void method. (And in that case, you can only return "nothing"!)
The Java Language Specification says this in ยง14.17:
A return statement with an Expression must be contained in one of the following, or a compile-time error occurs:
A method that is declared to return a value
....
If you have no value to return, then your choices are either to pick some value that means (to your application) "no value", or throw an exception.
The value null is often used to signify "no value", but you can use other things ... depending on the declared return type.
Throwing an exception would a bad whay to deal with this, unless "no result" is truly an exceptional outcome. Using exceptions and exception handling for normal flow control is a considered to be bad design in Java, and is liable to lead to serious performance problems.
It is also theoretically possible to terminate the JVM by calling System.exit(...), or write the method so that it runs forever or goes to sleep forever. However these are most likely "undesirable" behaviours.
You can always throw the Exception
if(conditionNotMet){
throw new YourCustomException();
}
then Handle it in whichever way you want !!!!
A method either return nothing (void), or something (including null), but can throw an Exception.
You have to think about how clients of the class will use the method. An exception really mean that the no return case should not occur in normal conditions.
Assuming the method is in a Foo class:
public class Foo {
private ClassXPto classXPto;
public ClassXPto getClassXPto() {...}
// other Foo stuff
}
In the client code:
Returning null
Foo foo; // initialized somewhere
ClassXPto x = foo.getClassXPto("abc", new Date());
if (x != null) {
// do something with x
}
Throwing/catching an exception
Foo foo; // initialized somewhere
try {
ClassXPto x = foo.getClassXPto("abc", new Date());
// do something with x
}
catch (WhatEverExceptionYouChoose e) {
// process the exception
}
Propagating an exception
Foo foo; // initialized somewhere
ClassXPto x = foo.getClassXPto("abc", new Date());
// do something with x. This point will be reached only
// if there is no exception thrown by getClassXPto()
If your method is designed in such a way that the return parameter is optional, you could use the new Optional mechanisms in Java 8.
Instead of returning null you would return Optional.empty().
For more information visit https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

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.

Categories

Resources