How to throw three exception in boolean method? - java

I am new to the Java World and I am trying to understand exceptions but what I didnt get is;
How can I throw an exception in boolean method?
And what to do when I have to use three Exceptions in one catch?
#Override
public boolean isValid(Object bean, ConstraintValidatorContext ctx) {
try {
if (Assert.isNull(bean)) {
logger.info(EXC_MSG_BEAN_NULL, bean.toString());
}
String dependentFieldActualValue;
dependentFieldActualValue = BeanUtils.getProperty(bean, dependentField);
boolean isActualEqual = stringEquals(dependentFieldValue, dependentFieldActualValue);
if (isActualEqual == ifInequalThenValidate) {
return true;
}
return isTargetValid(bean, ctx);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
logger.info("Necessary attributes can't be accessed: {}", e.getMessage());
//I cant throw an exception here...
}
}
or i can do this but it didnt also helped me: I have no idea how to use exception in boolean method.
#Override
public boolean isValid(Object bean, ConstraintValidatorContext ctx) {
try {
if (Assert.isNull(bean)) {
logger.info(EXC_MSG_BEAN_NULL, bean.toString());
}
String dependentFieldActualValue;
dependentFieldActualValue = BeanUtils.getProperty(bean, dependentField);
boolean isActualEqual = stringEquals(dependentFieldValue, dependentFieldActualValue);
if (isActualEqual == ifInequalThenValidate) {
return true;
}
return isTargetValid(bean, ctx);
} catch (ReflectiveOperationException e) {
logger.info("Necessary attributes can't be accessed: {}", e.getMessage());
//Here should be my throw new ReflectiveOperationException("ERROR");
}
}

You can't throw an exception at the indicated point because the method isValid doesn't include any Exception's in the signature. For pedagogical purposes, let's define a custom exception type:
static class MyException extends Exception {
public MyException(Exception e) {
super(e);
}
}
And then we can add throws MyException to the method signature of isValid and actually throw it in the multi-catch. Like,
#Override
public boolean isValid(Object bean, ConstraintValidatorContext ctx) throws MyException {
try {
// ...
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
logger.info("Necessary attributes can't be accessed: {}", e.getMessage());
throw new MyException(e);
}
}
If you want those specific exceptions to return up the call stack - just add them to the throws line and remove the try-catch (or re-throw in the try-catch if you really want to log here for some reason).
#Override
public boolean isValid(Object bean, ConstraintValidatorContext ctx)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
// No try-catch. Otherwise the same.
}

There are 2 ways to work with exception:
Do something with it now
Throw it (do something with it later)
As I understand you can't throw exception there because your method doesn't allow to throw exception, so you should deal with all checked exceptions within this method. Or you can add keyword "throws":
isValid(...) throws NoSuchMethodException {
...
throw e;
}
and this would allow you to throw exception of class NoSuchMethodException.

You only want to catch the three exceptions you expected,but in java ,any exception you don’t catch or throw it,the java application will crash.you do like this is nonsense

The problem here is that your class is implementing javax.validation.ConstraintValidator. The signature of the method isValid is defined in that interface as boolean isValid(T value, ConstraintValidatorContext context);. That's why you can't throw a checked exception from your implementation - you would violate the interface. Otherwise, if you were implementing a method in a class which doesn't implement any interface, or implements some interface you can change, you'd be able to change the method signature and throw exceptions at will.

Related

return dummy interface instance?

I have example code from a third party related to some API. It doesn't run because of an unhandled exception in a return statement.
The problem: The return type is an interface whose instances are always created with complicated factories (assume I do not have access to these). Thus even if I handle the exception in the stupid do-nothing way, I still can't return a valid dummy object.
public FunnyInterface calculateSomething()
{
return builder.someFunnyInterface(); // throws Exception
}
To get this code to run, is there anything I can do not involving:
modifying the code along the route where calculateSomething() is called,
finding a builder in the API that won't throw an Exception, or
manually writing a dummy class implementing the interface
?
Since you wrote that you can't call the builder, I guess that you are not interested in the value of type FunnyInterface, so just return null.
public FunnyInterface calculateSomething() {
try {
return builder.someFunnyInterface(); // throws Exception
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Or just
public FunnyInterface calculateSomething() {
return null;
}
I'd recommend a simple rethrow with wrapped in a RuntimeException so you don't need to declare a checked exception:
// Dummy mockup interface + function
public static interface FunnyInterface {}
public static FunnyInterface builder_someFunnyInterface() throws Exception { return null; }
public FunnyInterface calculateSomething() {
try {
return builder_someFunnyInterface(); // throws Exception
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I would not return null. If you don't have a meaningful way to handle the error, propagate it upwards to a level that does have a meaningful way to handle the error. If you really do want to return null/empty, then use Optional, otherwise throwing an unchecked RuntimeException is preferable.

JUnit TestWatcher : failed, is it possible to remove the thrown exception (manipulating Throwable/stacktrace)?

In JUnit, using a TestWatcher and Overriding the failed() function, is it possible to remove the thrown exception and instead make my own assertion?
The use case is : with functional tests on Android, when a test makes the app crashes, I would like to replace the NoSuchElementException with an AssertionError ("app crashed").
I have no problem to make the custom assertion (when I detect a crash in finished() method) , but how to remove the thrown exception ?
Because in my report it creates for one test the exception and the assertion, so there are more failures than test in failure, which is logic but annoying.
I was wondering if there were a way to customize the Throwable object to remove the specific NoSuchElementException, manipulating the stacktrace.
I didn't manage to do it. (And necessarily I don't want to perform it using a try/catch in every tests ...).
You could override TestWatcher.apply and add a special catch for NoSuchElementException:
public class MyTestWatcher extends TestWatcher {
public Statement apply(final Statement base, final Description description) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
startingQuietly(description, errors);
try {
base.evaluate();
succeededQuietly(description, errors);
}
catch (NoSuchElementException e) {
// ignore this
}
catch (AssumptionViolatedException e) {
errors.add(e);
skippedQuietly(e, description, errors);
}
catch (Throwable e) {
errors.add(e);
failedQuietly(e, description, errors);
}
finally {
finishedQuietly(description, errors);
}
MultipleFailureException.assertEmpty(errors);
}
};
}
You can do it by bypassing. An example code is given below. Hope it will help you.
try {
// Write your code which throws exception
----
----
----
} catch (NoSuchElementException ex) {
ex.printStackTrace();
if (ex instanceof NoSuchElementException) { // bypass
// NoSuchElementException
// You can again call the method and make a counter for deadlock
// situation or implement your own code according to your
// situation
AssertionError ("app crashed");
if (retry) {
---
---
return previousMethod(arg1, arg2,...);
} else {
throw ex;
}
}
} catch (final Exception e) {
e.printStackTrace();
throw e;
}
I have solved this type of issue previously. My another answer has details. You can go through my another answer: android.security.KeyStoreException: Invalid key blob

How do you throw an instance of an Exception class created through reflection?

I am trying to create a function that throws an exception based on the type that you pass in.
private void myFunc(Class<?> exceptionType) {
...do some work...
throw new exceptionOfTypeExceptionTypePassedIn(newMessage);
}
Can you do this?
First, the throw statement only works with reference expressions of Throwable or its subtypes. Therefore, the expression you pass to your throw must have that type. You can achieve this, by providing a bound for the exceptionType parameter.
private void myFunc(Class<? extends Throwable> exceptionType) {
If you now want to restrict the type of Throwable subtype, you can do that too.
If it's Exception, you'll need a throws declaration
private void myFunc(Class<? extends Exception> exceptionType) throws Exception {
If it's RuntimeException, it won't
private void myFunc(Class<? extends RuntimeException> exceptionType) {
Depending on what you need, you might actually make the method generic. It would then look like this
private <T extends Throwable> void myFunc(Class<T> exceptionType) throws T {
As for the actual reflection logic, you are making the assumption that the corresponding type has an accessible constructor which accepts a String argument. If it doesn't, Java will throw all sorts of exceptions of its own. You need to handle these.
A potential solution would look like this (javadoc for Class#getConstructor, javadoc for Constructor#newInstance)
private <T extends Throwable> void myFunc(Class<T> exceptionType) throws T {
final String message = "some message";
try {
throw exceptionType.getConstructor(String.class).newInstance(message);
} catch (InstantiationException e) {
e.printStackTrace();
// rethrow
} catch (IllegalAccessException e) {
e.printStackTrace();
// rethrow
} catch (IllegalArgumentException e) {
e.printStackTrace();
// rethrow
} catch (InvocationTargetException e) {
e.printStackTrace();
// rethrow
} catch (NoSuchMethodException e) {
e.printStackTrace();
// rethrow
} catch (SecurityException e) {
e.printStackTrace();
// rethrow
}
}
You can obviously collapse all those exception types into a multi-catch statement.
Note that if the exception type you passed in was one of those mentioned in the existing catch statements, it will be swallowed, ie. not thrown. You can also add all those in a throws declaration of its own.
private static <T extends Throwable> void myFunc(Class<T> exceptionType) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, T {
final String message = "some message";
throw exceptionType.getConstructor(String.class).newInstance(message);
}
or rethrow the caught exceptions wrapped in a RuntimeException.
You could use the newInstance method on the Class object.
Reflection is pretty messy. The accepted answer works, but your code will be harder to follow. You're probably better off refactoring your code to avoid this situation.

Custom Exception that wraps Multiple Exceptions : Encouraged or Not?

I am coding a Java Library that will be used to access a DB.
I am throwing the exceptions to the end-programmer who uses the JAR library to handle it the way he/she wants.
I wrote a custom Exception (provided below) to wrap connection specific exceptions together so the end-programmer will not have to catch all these exceptions in his code. (to make it easy for him)
is this a good practice when it comes to coding Java libraries?
By using this the user will only have to catch NConnectionException in his code.
public class NConnectionException extends Exception {
private static final Logger logger = LoggerFactory.getLogger(NConnectionException.class);
public NConnectionException(Exception e) {
if (e instanceof NullPointerException) {
logger.error("ERROR IN READING DF");
e.printStackTrace();
}
else if (e instanceof FileNotFoundException) {
logger.error("FILE NOT FOUND");
e.printStackTrace();
} else if (e instanceof ParserConfigurationException)
{
logger.error("PARSE CONF ERR");
e.printStackTrace();
}
else if (e instanceof org.xml.sax.SAXException)
{
logger.error("SAX ERR");
e.printStackTrace();
}
else if (e instanceof IOException)
{
logger.error("IO ERR");
e.printStackTrace();
}
}
}
You can pass a cause (Throwable) to a custom exception. Look at the Exception javadoc for more Information.
Edit:
public class CustomException extends Exception {
public CustomException(Throwable t) {
super(t);
}
}
public void testMethod(String s) throws CustomException {
try {
int integer = Integer.parseInt(s);
} catch (NumberFormatException e) {
throw new CustomException(e);
}
}
try {
testMethod("not a number");
} catch (CustomException ce) {
ce.printStackTrace(); // this will print that a CustomException
// with the cause NumberFormatException has occured.
ce.getCause(); // this will return the cause that
// we set in the catch clause in the method testMethod
}
According to this post, wrapping all the exceptions in a single is not good.
If you want to wrap them then
As your program will throw only one exception at a time then no need to store list of exceptions in NConnectionException.
And you can create a single object of exception in NConnectionException class. You can refer this structure.
And store the thrown exception in that object and throw back newly created object of NConnectionException class. Let the calling program catch NConnectionException exception and take out the stored object and act accordingly.
Note : Generally we don't handle unchecked exception (like NullPointerException), calling program will take care of it.

Issue with Exception type handling when not throwing them - wanting a more generic version of multi-catch

Sorry for the TL;DR, but I feel like it needs some explanation or it will be misunderstood.
I have a method that makes a call to (generally external) code which I expect to sometimes throw a RuntimeException, and uses futures which can throw InterruptedException or ExecutionException, and I want to be able to return an ordered set of returned values to from the call up until the exception was thrown, and the exception that was thrown. I wrote something that works, but unfortunately, the way the code looks makes me feel like I'm doing something wrong. What I think I really want is multi-catch to be a more generic concept that. That would allow pretty clean code to solve it, kind of like this:
public class SomeResults {
private final Set<SomeReturnType> valuesReturned;
private final #Nullable RuntimeException | ExecutionException | InterruptedException exception;
public SomeResults(Set<SomeReturnType> valuesReturned, RuntimeException | ExecutionException exception {
this.valuesReturned = valuesReturned;
this.exception = exception;
}
public Set<SomeReturnType> getValuesReturned() {
return valuesReturned;
}
public #Nullable RuntimeException | ExecutionException | InterruptedException getException();
}
And have a method that wraps up making the calls to the external code
...
generateResults(Bar bar) {
// Setup code
Set<SomeReturnType> valuesReturned = new LinkedHashSet<>();
...
// loop
{
// stuff
... // exceptions in this method should throw except for this one external code call
try {
valuesReturned.add(externalCodeCallGetSomeReturnValue(bar))
}
catch( RuntimeException | ExecutionException | InterruptedException e) {
return new MyResults(valuesReturned, e)
}
...
}
return new MyResults(valuesReturned, (RuntimeException | ExecutionException | InterruptedException) null);
}
And subsequently do
SomeResults myResults = foo.generateResults(new Bar());
if(myResults.getException() != null) {
throw(myResults.getException);
}
Etc. Note that I do note always want to immediately rethrow the exception - it depends on who is using these results what they will want to do with them. I might do something like
try {
SomeResults myResults = foo.generateResults(new Bar());
Foobar Foobar = new Foobar(myResults);
}
catch(Exception e) {
// I don't want to see any exceptions from externalCodeCallGetSomeReturnValue(bar) here
...
}
Of course, I could let the exception get thrown in the function that generates results, instead of catching the exception and returning it as a result. This has two pretty big issues:
1. Now returning the set of values is going to be awkward - I could perhaps pass in a Set to the method that needs to "return" results and it modifies that set instead of returning a set. That allows the set to be up to date when the exception is returned. Eg
generateResults(Bar bar, Set<SomeReturnType> orderedListForMeToWrite) throws ExecutionException, InterruptedException
What if code surrounding the external method call throws a runtime exception? Now I have no easy way of distinguishing if the exception call was from the actual call to the external code, or something else! I actually ran into this issue when attempting this design. The code threw IllegalArgumentException from somewhere else, and my code handling treated it as if it had been thrown from SomeReturnType externalCodeCallGetSomeReturnValue(Bar bar). This seemed like a code health issue, which is why I moved away from this solution.
The solution I went with is to just store the exception as an Exception. However, I hated losing that type information. With no additional code work, if something wanted to throw it, it will have to declare "throws Exception", which is not good, similar code health issues there. Is there a good way to handle this situation?
What I ended up doing to get it to work the way I wanted it to is as follows:
public static class SomeResults {
private final Set<SomeReturnType> orderedReturnValues;
private final #Nullable Exception exception;
AsyncEchoesResult(Set<SomeReturnType> responses) {
this.orderedResponses = responses;
this.exception = null;
}
AsyncEchoesResult(Set<SomeReturnType> responses, RuntimeException exception) {
this.orderedResponses = responses;
this.exception = exception;
}
AsyncEchoesResult(Set<SomeReturnType> responses, ExecutionException exception) {
this.orderedResponses = responses;
this.exception = exception;
}
AsyncEchoesResult(Set<SomeReturnType> responses, InterruptedException exception) {
this.orderedResponses = responses;
this.exception = exception;
}
public Set<SomeReturnType> getResponses() {
return orderedResponses;
}
public #Nullable Exception getException() {
return exception;
}
public void throwExceptionIfExists() throws ExecutionException, InterruptedException {
try {
throw (exception);
}
catch (RuntimeException | ExecutionException | InterruptedException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException("Unexpected exception type in SomeResults",e);
}
}
}
Obviously, this is pretty ugly. If I hate the constructors as they are I can easily enough replace them with a single one that takes an Exception, but that weakening the type-checking to only the runtime call of throwException(). Anyway, are there alternatives that work better? Note that I'm using with JDK 7 so while JDK 8 answers would be interesting, that won't fix it for what I'm working on.
Since Java doesn’t allow declare a variable as “one of these types” you have to encapsulate the exception using the only construct which supports such a type set: a piece of code throwing that exception.
Consider the following type definitions:
interface ReThrower {
void reThrow() throws RuntimeException, ExecutionException, InterruptedException;
}
static class MyResult
{
private final Set<SomeReturnType> valuesReturned;
private final #Nullable ReThrower exception;
public MyResult(Set<SomeReturnType> valuesReturned, ReThrower exception) {
this.valuesReturned = valuesReturned;
this.exception = exception;
}
public Set<SomeReturnType> getValuesReturned() {
return valuesReturned;
}
public void reThrowException()
throws RuntimeException, ExecutionException, InterruptedException
{
if(exception!=null) exception.reThrow();
}
}
Then you can create a MyResult like this:
MyResult generateResults(Bar bar) {
// Setup code
Set<SomeReturnType> valuesReturned = new LinkedHashSet<>();
// …
// loop
{
// stuff
// … exceptions in this method should throw except for this one external code call
try {
valuesReturned.add(externalCodeCallGetSomeReturnValue(bar));
}
catch( RuntimeException | ExecutionException | InterruptedException e) {
// In Java 8 you would say: new MyResult(valuesReturned, ()->{ throw e });
return new MyResult(valuesReturned, new ReThrower() {
public void reThrow()
throws RuntimeException, ExecutionException, InterruptedException {
throw e;
}
});
}
//...
}
return new MyResult(valuesReturned, null);
}
Note that the inner class (or lambda expression in Java 8) implicitly stores the exception and that that implicit variable has the desired “one of the listed exception type”. Then, you can safely re-throw the exception:
MyResult results = new MultiCatchAndStore().generateResults(new Bar());
try
{
results.reThrowException();
} catch(RuntimeException | ExecutionException | InterruptedException ex)
{
// handle, of course, you could also have separate catch clauses here
}

Categories

Resources