This question already has answers here:
Java 8: How do I work with exception throwing methods in streams?
(7 answers)
Closed 2 years ago.
public int deleteMultipleEntries(String[] idArray) throws Exception {
int result = dao.deleteMultipleEntries(idArray);
cache.invalidateAll(Arrays.stream(idArray).collect(Collectors.toList()));
if (result != idArray.length) {
Arrays.stream(idArray).forEach(s -> {
try {
cache.get(s);// this method throws ExecutionException if entry with id s not found
log.error("id:" + s + " was not deleted");
log.info("Deleting entry id:"+Integer.valueOf(s));
dao.deleteEntry(Integer.valueOf(s));//getting unhandled exception: java.lang.Exception error in IDE
} catch (ExecutionException e) {
log.info("id:" + s + " is deleted or it never existed");
}
});
}
return result;
}
public int deleteEntry(Integer primaryKey) {
String deleteSql = String.format(getDeleteSql(), primaryKey);
if (log.isDebugEnabled())
log.debug("Deleting Entry with Key: {}", primaryKey);
int affectedRows = getJdbcTemplate().update(deleteSql);
if (log.isDebugEnabled())
log.debug("Updated {} Rows", affectedRows);
return affectedRows;
}
Getting error at this statement dao.deleteEntry(Integer.valueOf(s));
if an exception occurs while executing dao.deleteEntry(Integer.valueOf(s)); the catch block cannot catch the exception since it catches ""ExecutionException" specifically, Hence the function itself should throw exception automatically since its signature has throws statement.
the try catch block i have written is for handling logic handling, if i write the same statement outside the try catch, it doesn't give any error. I want to understand the behavior here. please kindly help
Thats because you are in Arrays.stream(idArray).forEach(...)
Change this to normal foreach and it would work.
public int deleteMultipleEntries(String[] idArray) throws Exception {
int result = dao.deleteMultipleEntries(idArray);
cache.invalidateAll(Arrays.stream(idArray).collect(Collectors.toList()));
if (result != idArray.length) {
for(String s: idArray) {
try {
cache.get(s);// this method throws ExecutionException if entry with id s not found
log.error("id:" + s + " was not deleted");
log.info("Deleting entry id:"+Integer.valueOf(s));
dao.deleteEntry(Integer.valueOf(s));//getting unhandled exception: java.lang.Exception error in IDE
} catch (ExecutionException e) {
log.info("id:" + s + " is deleted or it never existed");
}
}
}
return result;
}
Related
This question already has answers here:
Returning from a finally block in Java
(6 answers)
Closed 2 months ago.
I have a method handleException that return a ResponseEntity :
#ExceptionHandler({Exception.class})
public ResponseEntity handleException(Exception e) {
Map<String, String> data = new HashMap<>( );
List temp;
data.put( "message", e.getMessage() );
if (e instanceof MissingServletRequestParameterException) {
if ( e.getMessage().contains("countryName") )
{
temp = REP_MAP.get(Utility.HttpCode.REP_HTTP_CNABSENT);
} else{
temp = REP_MAP.get(Utility.HttpCode.REP_HTTP_DTABSENT);
}
data.clear();
data.put( "message", (String)temp.get(1));
return ResponseEntity.status((HttpStatus)temp.get(0)).body( data);
} else if (e instanceof CustomException) {
return ResponseEntity.status(((CustomException) e).getStatus()).body(data);
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(data);
}
and it was working fine before adding loggingInterceptor :
#Around("execution(* com.coviddata..*(..) )")
public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable {
Object temp = null;
String inputString = getInput(joinPoint);
logger.debug(inputString);
try{
temp = joinPoint.proceed();
}
catch (Exception e) {
logger.error( ERROR + " " + ((MethodSignature)joinPoint.getSignature()).getDeclaringTypeName() + " " + joinPoint.getSignature().getName() );
}
finally {
logger.debug( OUT + ((MethodSignature)joinPoint.getSignature()).getReturnType() );
return temp;
}
}
Now, i can log before and after of all methods. the problem is when an exception is thrown, this log method prevent my exception handler to be called and thus nothing is send to the user as ResponseENtity and even the joinPoin.proceed() return null.
I have tought to intercept all methods except handleException but I think this is not the problem. I think the solution of that. I want only to log when there is exception and return ResponseEntity.
Is there a way to exclude handleException method from being intercepted ?
I have first exclude the method handleException annotated with #ExceptionHandler as the following :
#Around("execution(* com.coviddata..*(..) )"
+ "&& !#annotation( org.springframework.web.bind.annotation.ExceptionHandler)")
I have added a flag that is been set to true when there is an exception, adding a return null at the end of the method ( not in finally) solve the problem, I dont know why :
#Around("execution(* com.coviddata..*(..) )"
+ "&& !#annotation( org.springframework.web.bind.annotation.ExceptionHandler)")
public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable {
Object temp = null;
String inputString = getInput(joinPoint);
logger.debug(inputString);
boolean flag = false;
try{
temp = joinPoint.proceed();
}
catch (Exception e) {
flag = true;
logger.error( ERROR + " " + ((MethodSignature)joinPoint.getSignature()).getDeclaringTypeName() + " " + joinPoint.getSignature().getName() );
throw e;
}
finally {
logger.debug( OUT + ((MethodSignature)joinPoint.getSignature()).getReturnType() );
if(! flag)
return temp;
}
return null;
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I was working on a program, a basic one that is based on command line input. I made a custom exception which should be triggered when users don't enter the second input, but whenever I do so, it throws array out of bound exception. What should I do in this situation?
package com.company;
public class Program2 {
public static void main(String[] args) throws MYex{
{
int a,b,c;
try
{
a=Integer.parseInt(args[0]); // getting data
b=Integer.parseInt(args[1]); // from command line
if( args[1]==null){
throw new MYex();
}
try
{
c=a/b;
System.out.println("Quotient is "+c);
}
catch(ArithmeticException ex)
{
System.out.println("Error in division !");
}
}
catch (MYex e){
System.out.println(e.toString());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array out of bound!");
}
finally
{
System.out.println("End of the progarm!!!");
}
}
}}
class MYex extends Exception{
#Override
public String toString() {
return " oops a Exception occured";
}
}
If the user passes only one argument the args array has only one element. Therefore the exception already occurs when you try to access args[1].
To prevent this check args.length before accessing args[1]:
a=Integer.parseInt(args[0]); // getting data
if (args.length == 1) {
throw new MYex();
}
b=Integer.parseInt(args[1]); // from command line
hello I have this programming assignment where I have to use the functions they gave us, as they give it to us to use, the problem i am encountering is the fact this has to be void and I am not allowed to use System.out.println(); either so my question is how to i return the exception without changing the method header or it using System.out.println();?
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
System.out.println("ITEM " + itemID + " DOES NOT EXIST!");
}
}
In your catch block do this:
catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException("ITEM " + itemID + " DOES NOT EXIST!");
}
You don't need to add a throw declaration to your method, since IndexOutOfBoundsException is a RuntimeException.
Where ever you call the function you can add a catch block to read the error message like this:
catch (IndexOutOfBoundsException ex) {
System.out.println(ex.getMessage());
}
Well, if the method is used incorrectly (without validation of the index), maybe it should throw an exception?
You can remove the try-catch block completely. IndexOutOfBoundsException is a runtime exception, so it does not require the throws IndexOutOfBoundsException syntax.
However, if you want the exception to be less cryptic, you can wrap it with your own RuntimeException:
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
throw new RuntimeException("Invalid item ID: " + itemID, e);
}
}
You can change your method signature and throw an exception
public void deleteItem(String itemID) throws Exception{
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}catch (IndexOutOfBoundsException e) {
Exception ex = new Exception("ITEM " + itemID + " DOES NOT EXIST!");
throw ex;
}
}
Once done you can get your error message like this
try{
xxx.deleteItem("your itemID");
}catch(Exception e){
// You will read your "ITEM " + itemID + " DOES NOT EXIST!" here
String yourErrorMessage = e.getMessage();
}
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException( "ITEM " + itemID + " DOES NOT EXIST!");
}
}
public void deleteItem(String itemID)throws IndexOutOfBoundsException{
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
You cant return exceptions . Exceptions are thrown from the methods , you can use keyword throw for that.try above methods to throw exceptions from methods
Remove try..catch block and modify your function as
public void deleteItem(String itemID) throws IndexOutOfBoundsException{
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
Add try catch where you call this method and use System.out.println("ITEM " + itemID + " DOES NOT EXIST!"); there.
Ya even if you do not add throws to this method but put call of deleteItem in try catch block will work.
I am new to JUnit and I have to test a method using JUnit api. One method internall calls another. My test case goes inside the method but while catchign the exception it fails.
Method under test is
public void checkANDCondition( Map<String, Message> messagesMap ) throws EISClientException
{
List<String> codes = getMessageCodes();
if(isAllReturnedMessagesContainCodes(codes, messagesMap))
{
StringBuffer buff = new StringBuffer("All of the specified message codes matched returned errors.");
for(String code: codes )
{
Message message = messagesMap.get(code);
buff.append(message.getMessageCode() + ": " + message.getMessageType() + ": " + message.getMessageText() + " ");
}
throw new EISClientException(buff.toString());
}
}
public boolean isAllReturnedMessagesContainCodes(List<String> codes, Map<String, Message> messagesMap)
{
if(codes!=null)
{
for(String code: codes)
{
if(!messagesMap.containsKey(code))
{
return false;
}
}
}
return true;
}
What I have done so far is
#Test
public void testPostProcess() throws Exception {
clientResponse = mock(ClientResponse.class);
MessageToExceptionPostProcessFilter postProcessFilter = new MessageToExceptionPostProcessFilter();
RetrieveBillingServiceResponse serviceResponse = new RetrieveBillingServiceResponse();caughtException = false;
try {
postProcessFilter.setCondition(ConditionOperator.AND);
List<String> messagesCodes = new ArrayList<String>();
messagesCodes.add("200");
messagesCodes.add("400");
Message message = new Message();
message.setMessageCode("200");
message.setMessageType(MessageTypeEnum.MESSAGE_TYPE_INFO);
message.setMessageText("Service completed successfully");
serviceResponse.setMessages(Arrays.asList(message));
postProcessFilter.setMessageCodes(messagesCodes);
serviceResponse = postProcessFilter.postProcess(serviceResponse, clientResponse);
assertNotNull(serviceResponse.getMessages());
} catch (EISClientException ex) {
caughtException = true;
assertEquals("All of the specified message codes matched returned errors.", ex.getMessage());
}
assertTrue(caughtException);
}
How can I make it pass?
Thanks
#Test(expected = EISCLientException.class)
public void testPostProcess() throws Exception {
...
serviceResponse.getMessages();
fail("Shouldn't reach this point");
}
That way you don't need to catch, with expected if it does not get throw a EISClientException it will fail.
edit: There are two times I can think of where you wouldn't want to use this.
1) You are mocking exceptions that are thrown mock(exception.class);
this i believe then throws some Mockito excpetion and it will not match the expected exception.
2) You are wrapping caught exceptions in your code, and throwing a generic exception. Example of code:
try {
} catch (FileParseException e){
throw new (ProjectFailingException(e, "file is bad");
}
if you have multiple catches and are wrapping them as ProjectFailingExceptions then you may want to catch in the test like this...
#Test ( expected = FileParseException.class)
public void testProcess() {
try {
...
} catch (ProjectFailingException e){
throw e.getCause();
}
Then the proper exception is thrown and you can make sure that process isn't throwing an exception from a a different catch.
In my quest to learn Java better, I have been trying to understand exception handling. I cannot understand why the following code fails to compile.
The compiler message is:
TestExceptionHandling.java:12: error: exception StupidException is never thrown in body of corresponding try statement
catch (StupidException stupidEx) {
^
In the try block, method exTest.doExTest() is called. In this method I catch an InterruptedException and in its catch block I throw a new StupidException.
So why does the compiler say it's not thrown? What am I missing? Can any expert help me see my mistake please?
public class TestExceptionHandling {
public static void main(String argv[]) {
String output = "";
try {
output = "\nCalling method doExTest:\n";
exTest.doExTest();
}
catch (StupidException stupidEx) {
System.out.println("\nJust caught a StupidException:\n " + stupidEx.toString());
}
System.out.println(output);
}
}
class exTest {
static long mainThreadId;
protected static void doExTest() { //throws StupidException
mainThreadId = Thread.currentThread().getId();
Thread t = new Thread(){
public void run(){
System.out.println("Now in run method, going to waste time counting etc. then interrupt main thread.");
// Keep the cpu busy for a while, so other thread gets going...
for (int i = 0; i < Integer.MAX_VALUE; i++) {
int iBoxed = (int)new Integer(String.valueOf(i));
String s = new String("This is a string" + String.valueOf(iBoxed));
}
// find thread to interrupt...
Thread[] threads = new Thread[0];
Thread.enumerate(threads);
for (Thread h: threads) {
if (h.getId() == mainThreadId) {
h.interrupt();
}
}
}
};
t.start();
try {
Thread.sleep(5000);
}
catch (InterruptedException e){
System.out.println("\nAn InterruptedException " + e.toString() + " has occurred. Exiting...");
throw new StupidException("Got an InterruptedException ", e); // ("Got an InterruptedException. Mutated to StupidException and throwing from doExTest to caller...", e);
}
}
}
class StupidException extends Exception {
public StupidException(String message, Throwable t) {
super(message + " " + t.toString());
}
public String toString() {
return "Stupid Exception: " + super.toString();
}
}
Methods need to explicitly declare that they throw exceptions (with the exception of runtime exceptions, which are a bit different). Try declaring your doExTest method as
protected static void doExTest() throws StupidException {
...
}