How to handle both IOException and IIOException at the same time - java

Can anyone help me out how to catch both IOException and IIOException, because i need to differentiate image format and image load error.
Something like this is not working because i am not catching IOException.
catch (IIOException e)
{
System.out.println("Invalid image format: " + e.getMessage());
Throwable t = e.getCause();
if ((t != null) && (t instanceof IOException)) {
System.out.println("Unable to load image: " + e.getMessage());
}
}

Thats why we have separate catch statements:
try {
}
catch (ExceptionTypeA e1) { }
catch (ExceptionTypeB e2) { }
try {
bim=ImageIO.read(new File(....));
int[] a={2, 2, 3,4 };
a[7]=4;
}
catch (ArrayIndexOutOfBoundsException ex2) { System.err.println("error 2 "+ex2); }
catch (Exception ex) { System.err.println("error 1 "+ex); }
Exceptions need to be given in order of specificity; i.e. in your case,
catch (IIOException ex) { System.err.println("error 1 "+ex); }
catch (IOException ex2) { System.err.println("error 2 "+ex2); }

Have you tried something like this
catch(IOException e)
{
if(e instanceof IIOException)
{
System.out.println("Invalid image format: " + e.getMessage());
}else
{
System.out.println("Unable to load image: " + e.getMessage());
}
}

Related

Pattern matching in instanceof is not supported in version 6. Please I’m trying to catch duplicate entry error in jsp servlet

Please I’m trying to catch duplicate entry error in jsp servlet.
Here is my code
Insert Ignore into(…)
catch(SQLException E){
if(e instanceof SQLIntegrityConstraintViolationException e){
message= “Warning: “ + e.getMessage();
}
}
} catch (SQLException e) {
if (e instanceof SQLIntegrityConstraintViolationException) {
message = “Warning: “ + e.getMessage();
}
}
Or more honest about wiping an exception under the carpet:
} catch (SQLIntegrityConstraintViolationException e) {
message = “Warning: “ + e.getMessage();
} catch (SQLException e2) {
}
You do not need a SQLIntegrityConstraintViolationException variable.
And you might have casted it as
((SQLIntegrityConstraintViolationException)e).getMessage()

Exception handlers should preserve the original exception : Either log or rethrow this exception

This is my method, when I try to analyze my code by sonarQube am getting this error:
Exception handlers should preserve the original exception : Either log or rethrow this exception.
Why am getting this error, should I not catch the exception like my method?
my method :
for (String QT : Q_T) {
try {
// some logic
}
} catch (JsonParseException e) {
LOG.log(Level.SEVERE, e.toString());
} catch (JsonMappingException e) {
LOG.log(Level.SEVERE, e.toString());
} catch (IOException e) {
LOG.log(Level.SEVERE, e.toString());
}
catch (Exception e) {
LOG.log(Level.SEVERE, e.toString());
}
}
}
I believe what it's trying to tell you is to log the Exception as it is, not the toString() version, like here, also adding some 'context' or information to the log
for (String QT : Q_T) {
try {
// some logic
} catch (JsonParseException e) {
LOG.log(Level.SEVERE, "context", e);
} catch (JsonMappingException e) {
LOG.log(Level.SEVERE, "context", e);
} catch (IOException e) {
LOG.log(Level.SEVERE, "context", e);
} catch (Exception e) {
LOG.log(Level.SEVERE, "context", e);
}
}

Exception handling during database operations

I am bit curious to know in the below code snippet, is there any chances of database connection not being closed. I am getting an issue in the SonarQube telling "Method may fail to close database resource"
try {
con = OracleUtil.getConnection();
pstmtInsert = con.prepareStatement(insertUpdateQuery);
pstmtInsert.setString(++k, categoryCode);
pstmtInsert.clearParameters();
pstmtInsert = con.prepareStatement(updateQuery);
for (i = 0; i < userList.size(); i++) {
pstmtInsert.setString(1, p_setId);
addCount = pstmtInsert.executeUpdate();
if (addCount == 1) {
con.commit();
usercount++;
} else {
con.rollback();
}
}
}
catch (SQLException sqle) {
_log.error(methodName, "SQLException " + sqle.getMessage());
sqle.printStackTrace();
EventHandler.handle();//calling event handler
throw new BTSLBaseException(this, "addInterfaceDetails", "error.general.sql.processing");
}
catch (Exception e) {
_log.error(methodName, " Exception " + e.getMessage());
e.printStackTrace();
EventHandler.handle();//calling event handler
throw new BTSLBaseException(this, "addInterfaceDetails", "error.general.processing");
}
finally {
try {
if (pstmtInsert != null) {
pstmtInsert.close();
}
} catch (Exception e) {
_log.errorTrace(methodName, e);
}
try {
if (con != null) {
con.close();
}
} catch (Exception e) {
_log.errorTrace(methodName, e);
}
if (_log.isDebugEnabled()) {
_log.debug("addRewardDetails", " Exiting addCount " + addCount);
}
}
Thanks in advance
If you are using Java 7+, I suggest you use try-with-resources. It ensures the resources are closed after the operation is completed.
Issue has been resolved when I closed the first prepare statement before starting the another one.
added below code snippet after the line pstmtInsert.clearParameters();
try {
if (pstmtInsert != null) {
pstmtInsert.close();
}
} catch (Exception e) {
_log.errorTrace(methodName, e);
}

How to deal with timeout exception in Java?

Here is my code:
private void synCampaign() {
List<Campaign> campaigns;
try {
campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
} catch (ApiException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
e.printStackTrace();
} catch (RemoteException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
e.printStackTrace();
}
}
AdwordsCampaign.getAllCampaign() tries to get some remote resource. This may throw a RemoteException because the internet connection times out. When the exception is caught, I just want the thread to sleep for a while, then try to get the remote resource again.
Is there a problem with my code? Or is there a better way?
Nothing really wrong, but the (potentially infinite) retry loop with recursion (and the stack growing) makes me a little nervous. I'd write instead:
private void synCampaignWithRetries(int ntries, int msecsRetry) {
while(ntries-- >=0 ) {
try {
synCampaign();
return; // no exception? success
}
catch (ApiException e ) {
// log exception?
}
catch (RemoteException e ) {
// log exception?
}
try {
Thread.sleep(msecsRetry);
} catch (InterruptedException e1) {
// log exception?
}
}
// no success , even with ntries - log?
}
private void synCampaign() throws ApiException ,RemoteException {
List<Campaign> campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
}
This looks OK except the repetition of code in catch block(be sure of number of retries you want). You may want to create a private method to handle your exception as below:
private void synCampaign() {
List<Campaign> campaigns;
try {
campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
} catch (ApiException e) {
e.printStackTrace();
waitAndSync();
} catch (RemoteException e) {
e.printStackTrace();
waitAndSync();
}
}
private void waitAndSync(){
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
}
You indeed cannot catch it as a SocketTimeoutException. What is possible is to catch the RemoteException, retrieve it's cause and check if that's an instanceof SocketTimeoutException.
try{
// Your code that throws SocketTimeoutException
}catch (RemoteException e) {
if(e.getCause().getClass().equals(SocketTimeoutException.class)){
System.out.println("It is SocketTimeoutException");
// Do handling for socket exception
}else{
throw e;
}
}catch (Exception e) {
// Handling other exception. If necessary
}

Own exception in javame

Could I replace all the catches with one (self written) catch and switch between the types of exceptions caught in the self written one? That way I can easily put debugging on and of in the exception.
try {
int recordId = recordstore.addRecord(data, 0, data.length);
} catch (RecordStoreFullException e) {
e.printStackTrace();
System.out.println("debuginfo");
} catch (RecordStoreNotOpenException e) {
e.printStackTrace();
System.out.println("debuginfo");
} catch (RecordStoreException e) {
e.printStackTrace();
System.out.println("debuginfo");
} catch (NullPointerException e) {
e.printStackTrace();
System.out.println("debuginfo");
} catch (Exception e) {
e.printStackTrace();
System.out.println("debuginfo");
}
Is there any reason you don't do this?
try {
int recordId = recordstore.addRecord(data, 0, data.length);
} catch (Exception e) {
// or use a logging framework.
System.err.println("debuginfo");
e.printStackTrace();
}

Categories