Custom Exception that throws only specific Exceptions - java

I have a method which will throw SecurityException,NoSuchFieldException, IllegalArgumentException, IllegalAccessException.
I want to Custom Exception clause so that it will throw only the above Exception.
If any other exception comes, my Custom Exception clause should not throw it.
Is there a way or two to do this?
Thanks.

May be you can test the type of exception, for example:
if (e instanceof SecurityException) {
// do sth;
} else if (e instanceof NoSuchFieldException) {
// do sth;
} else if (e instanceof IllegalArgumentException) {
// do sth;
}

Related

How to re-throw a Throwable?

Consider this code:
#Test(expected = NullPointerException.class)
public void testSaveEmptyApplication() {
try {
Application application = new Application();
Application result = applicationService.save(application);
} catch (Exception e) {
if(e instanceof UncheckedServiceException) {
throw e.getCause(); // java.lang.Throwable, compiler error
}
}
}
How to re-throw a Throwable?
The problem is that testSaveEmptyApplication is not declared to throw any checked exceptions. But e.getCause() returns Throwable which is a checked exception. So what you are doing in your example code is breaking Java's checked exception rules.
If you know that the cause really is a RuntimeException, then you can do this
throw (RuntimeException) e.getCause();
Caveats:
However, if your assumption is incorrect and the cause exception's actual class is a checked exception, the above will result in a (brand new) ClassCastException which squashes the cause exception you were trying to rethrow.
The above will also break if the cause was an Error, but you could deal with that; e.g something like this.
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new AssertionError("Unexpected exception class", cause);
}
If you want to be able to rethrow checked exceptions, then they must be declared in the method signature. Once you have done that you can discriminate and throw them as per the above pattern.
This is all a bit cumbersome. But this is the price you pay for having wrapped the exception in the first place.
One solution I can think of for there is:
The catch clause to be:
try {
// ...
} catch (Exception e) {
if(e instanceof UncheckedServiceException) {
if(e.getCause() instanceof NullPointerException) {
throw new NullPointerException(e.getCause().getMessage());
}
}
}
Otherwise change the method signature like this:
public void method() throws Throwable {
// ...
}

What is the cleanest/correct way to handle Future.get() custom exceptions inside callable? (Advanced)

Code:
public void processData(PaymentRequest data) {
List<Payment> paymentList = new ArrayList<>();
List<Callable<Payment>> paymentCallables = new ArrayList<>();
data.getPaymentInfoList().forEach(payment -> paymentCallables.add(() -> payment.execute()));
try {
executorService.invokeAll(paymentCallables)
.stream()
.map(this::apply)
.forEach(paymentList::add);
} catch (InterruptedException exception) {
throw new ProcessorException("task interrupted when processing", exception);
}
}
private Payment apply(Future<Payment> paymentFuture) {
try {
return paymentFuture.get(); //Only shows ExecutuonException
} catch (InterruptedException | ExecutionException exception) {
throw new ProcessorException("task interrupted or failed", exception);
}
}
I have omitted some code for clarity.
BACKGROUND INFO
My system has a list of callables. In this list, there are some executions that will execute at a later date. The key thing to note is that the executions that will run have custom exceptions inside them.
When the code is run, and there is an exception in one of the callable executions. An exception is thrown; Specifically, this exception happens at paymentFuture.get().
THE PROBLEM
I have my own custom exceptions in payment.execute(). For example, I have a validation exception inside payments.execute() method. Example:
public void execute() {
try {
//process
} catch (
throw new ValidationException();
}
THE PROBLEM IS when this exception occurs, and ValidationException is thrown, this exception gets wrapped up by ExecutionException. So what is being handled is ExecutionException. So java wraps ExecutionException around my ValidationExecption. What I want is for a way to handle and throw ValidationException out of the class so it can be handled by another class GlobalExceptionHandler.
PS:
Doing:
throw exception.getCause()
Will not work because exceptions NEED to be handled with try/catch in the method and I would like to throw a new exception that can be caught by an external class.
Been trying to sort this out for hours so Im open for all ideas.
I believe the exceptions that may be thrown from the payment.execute method can be grouped by a common interface, let's say PaymentException.
ValidationException would extend PaymentException.
In this case, you would need to check exception.getCause() instanceof PaymentException and rethrow the cause if the condition is true.
try {
return paymentFuture.get();
} catch (InterruptedException | ExecutionException exception) {
final Throwable cause = exception.getCause();
if (cause instanceof PaymentException) {
throw (PaymentException) cause;
}
throw new ProcessorException("task interrupted or failed", exception);
}

How to throw three exception in boolean method?

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.

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.

Casting exceptions when rethrowing in Java

Compare these two methods:
void foo() throws SomeSuperException {
try {
//...
} catch (SomeSuperException e) {
if (e instanceof SomeSubException) {
throw e;
}
}
}
void bar() throws SomeSubException {
try {
//...
} catch (SomeSuperException e) {
if (e instanceof SomeSubException) {
throw (SomeSubException) e;
}
}
}
Aside from the method signatures (bar can declare throws SomeSubException instead of throws SomeSuperException), is there any practical difference between the two methods?
To be clear: I'm aware that this is a horrible approach to exception handling, and should not be done!
The difference is that in the first case, externally the caller doesn't know about your specific SomeSubException, so some detail is lost in translation.
No there's no (big) difference.
From the ordinary it's the best choice to throw the most specific exception,
no the super or broader one. This allows you to handle more cases in the overlaying catchBlock.

Categories

Resources