How to handle cause by Exception in a good Java way - java

I have some code in try-catch and in that code I am calling web service.On web service I have set timeout.
I have two web service call one taking no time its working fine and another one taking long to respond problem is not that but because of the time out it should throw SocketTimeoutException but its throwing PrivilegedActionException and after a long stack stace its showing cause by SocketTimeoutException.
I have intentionally put service call time very short to get SocketTimeoutException but its giving me PrivilegedActionException as a primary Exception.
I want to catch SocketTimeoutException and I'm not able to catch PrivilegedActionException becuase at the code level its showing PrivilegedActionException has not been thrown by this try catch.
I have written below code for achieve my goal but it's not working
try {
//some code here for service call
}catch(SocketTimeoutException e)
{
//not able to come here even though cause of the PrivilegedActionException is SocketTimeoutException
}
catch(Exception e)
{
//directly coming here OF COURSE
}
stacktrace:
java.security.PrivilegedActionException: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Message send failed
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: java.security.PrivilegedActionException: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Message send failed

you can catch PrivilegedActionException, and call getCause to get SocketTimeoutException. Maybe a while loop is needed if SocketTimeoutException is not a direct cause.
try{
}catch(PrivilegedActionException e){
Throwable tmp = e;
while(tmp != null){
if(tmp instanceof SocketTimeoutException){
SocketTimeoutException cause = (SocketTimeoutException) tmp;
//Do what you need to do here.
break;
}
tmp = tmp.getCause();
}
}
Temporary solution:
catch(Exception e){
if(e instanceof PrivilegedActionException){
//while loop here
}
}

Its better that you define your own Exception class and perform operations which are required.
Just make sure before throwing the exception you release all the resources which you have been using in your program.

Related

Java: Poor error handling, Throw inside Finally

I have the following code which I am running through fortify. Why it gets marked for poor error handling, throw inside finally?
private String getResourceContent(String fileName) throws IOException {
try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {
return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
} catch (NullPointerException n) {
throw new ErrorDescriptorException(
String.format("Error loading Error description data from Resource file [%s].", fileName), n);
}
}
Explanation
This is explained very well in the official documentation (see Poor Error Handling: Throw Inside Finally). Let me quickly quote the important sections:
Using a throw statement inside a finally block breaks the logical progression through the try-catch-finally.
In Java, finally blocks are always executed after their corresponding try-catch blocks and are often used to free allocated resources, such as file handles or database cursors. Throwing an exception in a finally block can bypass critical cleanup code since normal program execution will be disrupted.
So you can easily bypass cleanup code by doing that, which leads to resource leaks.
Although not directly visible in your code, you actually have a hidden finally block since you are using try-with-resources which automatically closes the resource in a finally block.
Also see Throwing an exception inside finally where this was already discussed.
Example
Here is an example from the official documentation:
public void processTransaction(Connection conn) throws FileNotFoundException {
FileInputStream fis = null;
Statement stmt = null;
try {
stmt = conn.createStatement();
fis = new FileInputStream("badFile.txt");
...
} catch (FileNotFoundException fe) {
log("File not found.");
} catch (SQLException se) {
// handle error
} finally {
if (fis == null) {
// This bypasses cleanup code
throw new FileNotFoundException();
}
if (stmt != null) {
try {
// Not executed if the exception is thrown
stmt.close();
}
catch (SQLException e) {
log(e);
}
}
}
}
The call to stmt.close() is bypassed when the FileNotFoundException is thrown.
Note
Why are you checking for null using a NullPointerException instead of a basic if-else? There is rarely ever a valid reason to catch a NullPointerException. Just do:
try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {
if (resource == null) {
// TODO Throw your exception here
}
return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
}
It might also help to improve the error message by telling the exact reason that the resource could not be found.
Consider the following code, which is loosely based on yours:
String throwing(InputStream inputStream) throws IOException {
try (InputStream resource = inputStream) {
return "good";
} catch (NullPointerException n) {
return "bad";
}
}
You see, no exceptions thrown here. Still, you cannot remove the throws IOException bit – how’s that? Well, InputStream#close() can throw it, and it will be in the implicit finally block that the try-with-resources statement created. I guess there’s not much you can do about it, it looks like a Fortify false positive.
Beyond the misleading message from your tool, there is actually is poor error handling in your code, for multiple of reasons:
catching NPE is really bad practice. Either it is a bug (something that is null and shouldn't), or your code is missing a check if (whatever == null) and the corresponding code to deal with that expected situation
assuming that this NPE has exactly that meaning that you express in your new Exception is well, just guessing
In other words: without further information, it is not clear what exactly your tool complains about. But: one doesn't need a tool to understand: this is poor error handling.
Beyond that, such tools typically give some sort of information about their warnings. Meaning: there might be an "error id" coming with that warning, and you should be able to look up that "error id" in the documentation of your tool for further explanations.

Continue for loop after exception java

This is my code:
if (Recipients_To != null) {
for (int i = 0; i < Recipients_To.length; i++) {
message.setRecipients(Message.RecipientType.TO, Recipients_To[i].toString());
Transport.send(message);
}
}
I have more than 500 Recipients list to send mail and this code will send personal mail to each recipients. But if i got exception in between this for loop i want to continue loop for remaining recipients. How can i do?
You want to use try catch blocks to do this, like so
for (int i = 0; i < Recipients_To.length; i++)
{
try {
message.setRecipients(Message.RecipientType.TO,Recipients_To[i].toString());
Transport.send(message);
}
catch (YourException e){
//Do some thing to handle the exception
}
}
This catches the potential issue and will still continue with the for loop once the exception has been handled.
You can catch the exception e.g.
try {
message.setRecipients(Message.RecipientType.TO, Recipients_To[i].toString());
Transport.send(message);
} catch (Exception e) {
// handle it or leave it be
}
Technically, it's simply a matter of catching the exception (see Murat K's answer). I would recommend, however, that since you're sending e-mail, that you do cease sending the rest when the first exception occurs, unless you are certain that it is an error you can safely ignore. A few examples of things that can go wrong:
Invalid credentials: this means that if you continue attempting to send, every subsequent attempt will also fail. Best case: no e-mail sent. Worst case: SMTP server blocks your access due to excessive login failures.
Malformed recipient address: no issue to continue trying the other addresses, but you need to do something with this error (remove recipient from list for future mailings)
Misconfigured mail server address: each iteration of your loop will try to connect to the mailserver, and fail. This will slow down the method tremendously (server timeouts) or spam your log (assuming you did something with the exception)
So please consider your course of action carefully when handling e-mail.
You can try something like this
if (Recipients_To != null) {
for (int i = 0; i < Recipients_To.length; i++) {
try {
message.setRecipients(Message.RecipientType.TO, Recipients_To[i].toString());
Transport.send(message);
} catch (Exception exp) {
//Log your exception here or do whatever you want to happen in case of exception
}
}
}

Weird bug in Java try-catch-finally

I'm using JODConverter to convert .xls and .ppt to .pdf format. For this i have code something like
try{
//do something
System.out.println("connecting to open office");
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
System.out.println("connection object created");
connection.connect();
System.out.println("connection to open office successful");
//do something
if(!successful)
throw new FileNotFoundException();
}catch(Exception e){
System.out.println("hello here");
System.out.println("Caught Exception while converting to PDF ");
LOGGER.error("Error in converting media" + e.getMessage());
throw new MediaConversionFailedException();
}finally{
decode_pdf.closePdfFile();
System.out.println("coming in finally");
//do something here
}
My Output :
connecting to open office
connection object created
coming in finally
P.S. return type of method is void
How is it possible ? Even if there is some problem in connection.connect(), it s'd come in catch block. confused
Perhaps an Error was thrown. This would still result in the try block not being completed, the catch Exception block ignored and the finally block being called.
try to catch Throwable, and watch stacktrace, maybe conection.connect() threw an Error (or other custom class which also extends Throwable).
If an error of type Error occurred, or worse, of type Throwable, then your catch handler for Exception wouldn't fire. Is it possible that you're getting some sort of VM error, or OOM, or stack overflow?
If so, this would account for the output you reported.
Depending on the implementation of OpenOfficeConnection Interface various types of throwables can be expected. It is possible that one of those throwables does not extend java.lang.Exception. Try to catch java.lang.Throwable instead

Catch Exception in finally { } ? Must?

I feel puzzle ...
I write a small routine in .jsp. Finally, ResultSet, Statement and Connection are required to be closed. I also write the closing codes in finally { }, but when the page is run, it return error that I didn't catch exception ...
I read some forum. Other people didn't catch any exception in finally { }
Any Hint ?
Sounds like you have the old problem of needing to close() in a finally block but close() throws an exception itself. Try somethig like the following...
ResultSet rs;
try {
// do various stuff
rs = ...;
} finally {
try {
if (rs != null) rs.close();
} catch (SQLException e) {
// do something with exception
}
}
You must catch exceptions in the code finally block. As you must catch exceptions in the catch block. Nested try/catches are a regular thing (albeit ugly).
One important note here is that you could have the exceptions that occur in finally declared in the throws clause of the method. However that would lead to the exception in finally overriding the original exception, which is lost. And you will see, for example, a NullPointerException, rather than FileNotFoundException.
By the way, avoid having code in the JSP file. Place it in a servlet.
finally{} doesn't do any exception catching. A finally{} block exists to make sure that certain code is run, no matter whether the try{} block reached its natural end or if it's jumping temporarily to the finally{} because an exception happened and that finally{} block was along the way. But after the finally{} finishes, the exception goes about its merry business, cavorting its way up the stack and cheerfully crashing your program.
If you want to actually catch the exception and stop it from unwinding the stack further, use catch(){}. But don't use catch blindly- catching an exception you don't actually know how to recover from is much worse than crashing, because now your program isn't working correctly and you don't have an exception stack trace telling you why.
Your ResultSet, Statement, and Connection almost certainly did get closed. And then the exception continued happening and crashed your program anyway, because that had nothing to do with your ResultSet, Statement, and Connection.
What was the actual exception?
Maybe I'm getting old, but what's wrong with catching exceptions in the catch block?
It helps if you say what is in your try block. You are probably not catching appropriate exception or your code in finally throws exception.
It is OK to have finally without catch.
try {
//do some work
}
finally {
//check of state and do clean up. You would have reached here via multiple branches.
}
It more appropriate to catch specific exceptions using catch and then handle specific cleanup there. Use finally for any code that must get executed even when exception happen.
try {
//do some work
}
catch ( RecoverableException1 re1) {
//cleanup
}
catch ( RecoverableException2 re2) {
//cleanup
}
finally {
//check of state and do clean up. You would have reached here via multiple branches.
}
finally{
try{
resultSet.close();
}catch(E e){
}finally{
try{
statement.close();
}catch(E e){
}finally{
conn.close();
}
}
}

Java exception handling

How do I use exceptions and exception handling to make my program continue even if an exception occurs while processing certain files in a set of files?
I want my program to work fine for correct files while for those files which cause an exception in program, it should ignore.
Regards,
magggi
for(File f : files){
try {
process(f); // may throw various exceptions
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
You have to use the try/catch/finally blocs.
try{
//Sensitive code
} catch(ExceptionType e){
//Handle exceptions of type ExceptionType or its subclasses
} finally {
//Code ALWAYS executed
}
try will allow you to execute sensitive code which could throw an exception.
catch will handle a particular exception (or any subtype of this exception).
finally will help to execute statements even if an exception is thrown and not catched.
In your case
for(File f : getFiles()){
//You might want to open a file and read it
InputStream fis;
//You might want to write into a file
OutputStream fos;
try{
handleFile(f);
fis = new FileInputStream(f);
fos = new FileOutputStream(f);
} catch(IOException e){
//Handle exceptions due to bad IO
} finally {
//In fact you should do a try/catch for each close operation.
//It was just too verbose to be put here.
try{
//If you handle streams, don't forget to close them.
fis.close();
fos.close();
}catch(IOException e){
//Handle the fact that close didn't work well.
}
}
}
Resources :
oracle.com - Lesson: Exceptions
JLS - exceptions
I guess your new to programming as execeptions are a fairly fundermental concept, as problems can happen out of your control and you need to deal with it.
The basic premise is a try catch block.
try
{
//Your code here that causes problems
}
catch(exception ex)
{
//Your code to handle the exception
}
You 'try' your code, and if an exception is raised, you 'catch' it. And do what you need.
There is also an addition to the catch block in that you can add finally{} below it. Basically even if no exception is raised the finally code is still run. You may wonder the point in this, but its often used with streams/file handling etc to close the stream.
Read more on java exceptions here in tutorials written by Sun (now Oracle)- http://download.oracle.com/javase/tutorial/essential/exceptions/
try
{
//Your code here that causes problems
}
catch(exception ex)
{
//Your code to handle the exception
}
finally
{
//Always do this, i.e. try to read a file, catch any errors, always close the file
}
The question you may ask is how do you catch different exceptions, i.e. is it a null reference, is it divide by zero, is it no file found or file not writeable etc. For this you write several different catch blocks under the try, basically one catch for each type of exception, the use of "exception" is basically a catch all statement, and like in stack of if statements if an "exception" is the first catch block it will catch everything, so if you have several catch blocks ensure exception is the last one.
Again, this is a useful but large topic so you need to read up about it.
Since you are doing multiple files, you need to basically do a loop and within the loop is contained the try/catch block.
so even if one file fails, you catch it, but carry on running, the code will then loop around onto the next file unhindered.
just catch the excpetion it may throw and do nothing with it; eat it as people say :)
But at least log it!
Very concise example:
try {
your code...
} catch (Exception e) {
log here
}
Typically, I would have done this.
ArrayList<Entry> allEntries = getAllEntries();
for(Entry eachEntry:allEntries){
try{
//do all your processing for eachEntry
} catch(Exception e{
ignoredEntries.add(eachEntry);
//if concerned, you can store even the specific problem.
} finally{
//In case of resource release
}
}
if(ignoredEntries.size() > 0){
//Handle this scenario, may be display the error to the user
}
FileSystemException may be the specific exception you are looking for.
Although, a better idea for beginners is to catch an exception and print it using
System.out.println(e);
where e is the caught exception.
public class Main
{
public static void main(String args[])
{
int a=10;
try
{
System.out.println(a/0); //Here it is not possible in maths so it goes to catch block
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception");
}
}
}
output:Arithmetic Exception
Exception in java are runtime error which can be handled by the program, the process is called as exception handling. Parent class of exception is Throwable.
Exception : Exception are those runtime error which can be handled by program.
Error : Those runtime error which can’nt handled by the program.
Tools used to handle Exception:
Try
Catch
Finally
Throw
Throws
more

Categories