Library thrown exceptions - java

I have project as a "library" which does HttpCommunication. I post data into it and receive response. Lib's method can throw several exceptions which I want catch in the hosted app, but somehow I can catch only general Exception instead of specific once.
Library method code:
public byte[] execute(String entityStr) throws UnsupportedEncodingException,
ClientProtocolException, IOException
{
...
// some code that can throw mentioned exceptions
}
Hosted class:
try {
byte[] response = httpClient.execute(profile);
} catch (Exception e) {
e.printStackTrace();
}
code above compiles, but code below does not.
try {
byte[] response = httpClient.execute(profile);
} catch (UnsupportedEncodingException e) {
} catch (ClientProtocolException e) {
}
Exception objects marked as errors, messages say
Unreachable catch block for UnsupportedEncodingException. This exception is never thrown from the try statement body.
Hosted class is an Activity. Communication done in AsyncTask class.
If anybody knows what's wrong with it, explain me please.

Most likely you need to clean and rebuild--if you're calling the method you think you are, and the signature is as shown, it pretty much has to work.

Related

How to handle different exception http types with try-catch in Java?

I am a beginner in API with Java, I am writing the RESTful APIs, and now I need to write the API Handler to handle the request from the front-end. Just noticed there are so many kinds of HTTP error when handling the request.
So I am wondering how to catch these exceptions with try-catch in Java.
I did one very basic try-catch to handle the InvalidRequestException, which refers to the exception from the client side.
#Override
public String handle(final APIGatewayProxyRequestEvent event) {
if (event.getHttpMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
try{
FeatureRecord featureRecord = Jackson.fromJsonString(event.getBody(), FeatureRecord.class);
featureProcessor.createFeature(featureRecord);
return EMPTY_STRING;
} catch (Exception ex) {
throw new InvalidRequestException(ex);
}
}
Now I want to split the exception type to distinguish different HTTP exceptions, like this:
#Override
public String handle(final APIGatewayProxyRequestEvent event) {
if (event.getHttpMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
try{
FeatureRecord featureRecord = Jackson.fromJsonString(event.getBody(), FeatureRecord.class);
featureProcessor.createFeature(featureRecord);
return EMPTY_STRING;
} catch (InvalidRequestException ex) {
throw new InvalidRequestException(ex);
} catch (ServiceInternalException ex) {
throw new ServiceInternalException(ex);
} ... ...
}
But I don't know how to write the catch sections.
I know there are many exception types from https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500, but how to handle them with try-catch? Do I need to write the new Exception type?
Catching more exception types
You can catch several exception types with a single catch if you catch their common ancestor class. For example
try {
//some code
} catch (Exception ex) {
//handling the catch
}
will catch all exceptions, so please be as general as possible, but still handle the errors properly, so catching Exception might be or might not be an option for you, depending on your situation.
Ways to handle an exception
You are catching several exception types and instead of handling them or throwing them, you throw an exception of the same type. For instance there is no reason to do this:
try {
//some code
} catch (InvalidRequestException ex) {
throw new InvalidRequestException(ex);
}
instead of this:
try {
//some code
} catch (InvalidRequestException ex) {
throw ex;
}
But if your catch is only throwing the same exception, then there is no point having the catch at all. You would need to make the errors user-friendly, that is, send a response to the user explaining the problems and then throw the exception. Or, you can avoid throwing the exception at all inside the catch and log some message instead.
Implementing your own Exception
This is of course an option and could be feasible if you have some custom error types.

How should I use IOException in `try-with-resources` nested in the method with`throws IOException` in the header?

AFAIK, the standard try-with-resources form
try(InputStream is= new ...){
... some reading from is
} catch (..){
... catching real problems
}
catch (IOException e) {
... if closing failed, do nothing - this clause is demanded by syntax
}
is equivalent to:
try{
InputStream is= new ...
... some reading from is
} catch (..){
... catching real problems
} finally {
try{
is.close();
} catch (IOException e) {
... if closing failed, do nothing
}
}
The first variant is more simple, of course. But I see the case when the second variant is absolutely OK, whereas the first becomes ununderstandable.
Imagine the situation, when you have got code, where the try(){} appears in the function with throws IOExceptions clause.
String readFromFile(...) throws IOException{
...
try(...){
...
}
}
The IOException in the second catch eats all IOExceptions, either connected to the attempt of closing or not. And does nothing. I suppose, that somewhere out of the method there is a piece of code that works with that IOException and does something noticeable. For example, logs the stack. So, local catches will be never reached. We are not interested in the second catch clause, but usually, we need some special reaction for the first one.
On the other hand, if we delete the closing catch(IOException e){} clause, counting on the throws in the method header, that absolutely uninteresting for us closing exception will be reacted to.
While we are catching the closing problems by IOException, I see no way out of the problem. And Eclipse java editor demands me to use this very exception for that clause!
How can I divide IOException appearing from closing from other IOExceptions, appearing in the try{} body?
I think Java is to blame for this one. The close() method should have thrown a different exception than IOException there is rarely anything the caller can do about it. Your only solution is to rewrap the IOExceptions you're interested in before rethrowing.
Usually what I do is I extract the entire content of the try-block to its own method where I can catch any IOExceptions and re-throw them as custom exceptions. I can then catch the remaining IOException by itself in the catch block.
public void foo() throws CustomException {
try (InputStream is= new ...) {
bar(is); //This catches internal IOExceptions and throws a CustomException
}
catch (IOException e) { //The close() exception
}
}

Should I re-throw an exception after logging it?

I find myself coding methods that throw a specified error, but still surrounding the relevant code sections in a try catch, where I use the catch to log a localised error message and re-throw the principal one.
Here is a short example:
public void doWork(String url) throws IOException {
Object target;
try {
target = new target(url); //instantiating this object could potentially not work if the URL is malformed
} catch (MalformedURLException e) {
localErrorMessage(debug, "URL error here"); //log a local message
throw e;
} catch (IOException e) { //in some cases it can throw an IO exception if using a localised file type object.
localErrorMessage(debug, "IO error here"); //log a local message throw e;
}
}
I use this as I can turn off my localised logging (using log4j2), or use it during testing, as a debugging method.
Is this a reasonable practice, or is there a better way to do it?

Difference between catching exceptions using Exception class or FileNotFoundException class

Like i have these two scenarios where we have to handle FileNotFoundException
Case1:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Case2:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (Exception e) {
e.printStackTrace();
}
In both cases printed Stack Trace is same. I would like to know the difference between both implementations and what should be preferred ?
From the docs it gives the reason:
"A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass."
Exception class is the parent of all the other exception class. So if you know that you are going to get the FileNotFoundException then it is good to use that exception. Making the Exception is a generic call.
This would help you understand:
So as you can see that the Exception class is at a higher hierarchy, so it means it would catch any exception other than the FileIOExcetion. But if you want to make sure that an attempt to open the file denoted by a specified pathname has failed then you have to use the FileIOExcetion.
So here is what an ideal approach should be:
try {
// Lets say you want to open a file from its file name.
} catch (FileNotFoundException e) {
// here you can indicate that the user specified a file which doesn't exist.
// May be you can try to reopen file selection dialog box.
} catch (IOException e) {
// Here you can indicate that the file cannot be opened.
}
while the corresponding:
try {
// Lets say you want to open a file from its file name.
} catch (Exception e) {
// indicate that something was wrong
// display the exception's "reason" string.
}
Also do check this: Is it really that bad to catch a general exception?
In case 2, the catch block will be run for all Exceptions that are caught, irrespective of what exception they are. This allows for handling all exceptions in the same way, such as displaying the same message for all types of exceptions.
In case 1, the catch block will be run for FileNotFoundExceptions only. Catching specific exceptions in different catch blocks allows for the handling of different exceptions in different ways, such as displaying a different message to the user.
When an exception occures the JVM throws the instance of the Exception and that instance is passed to the respective catch block , so in catch(Exception e) e is just the reference variable , but the instance it points to is of Exception thrown .
In case of catch(FileNotFoundException e) , e is also a reference variable and the instance it points to is of Exception thrown , so in both cases different reference varibales (i.e. e) are pointing to the instance of same the Exception (which is thrown) .
this is what i prefer :
try {
// some task
} catch (Exception e) {
if (e instanceof FileNotFoundException) {
// do this
}
if (e instanceof NullPointerException) {
// do this
} else {
// do this
}
}
It is a matter of what you want to intercept. With Exception you will catch any exception but with FileNotFoundException you will catch only that error case, allowing the caller to catch and apply any processing.
When you write this:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The code inside the catch block is only executed if the exception (thrown inside the try block) is of type FileNotFoundException (or a subtype).
When you write this, on the other hand:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (Exception e) {
e.printStackTrace();
}
the catch block is executed for any exception (since Exception is the root type of any exception).
If your file (test1.txt) does not exist, a FileNotFoundException is thrown and both code snippets are able to catch it.
Try and change it to something like:
try {
FileInputStream fis = new FileInputStream("test1.txt");
} catch (NullPointerException e) {
e.printStackTrace();
}
and you will see that the catch block is no longer executed.
Exception class is the parent of FileNotFoundException.
If you have have provided the Exception in the catch statement, every Exception will be handled in the catch block. But if FileNotFoundException is present in catch block, only exceptions rising due to absence of a File at said source or permissions not available to read the file or any such issues which makes spoils Java's effort to read the file will be handled. All other exceptions will escape and move up the stack.
In the code snippet provided by you, it is fine to use both. But i would recommend FileNotFoundException as it points to exact issue in the code.
For more detail you can read Go Here
Don't use any of those.
Don't catch Exception. Why? Because it also catches all unchecked exceptions (ie, RuntimeExceptions and derivates). Those should be rethrown.
Don't use the old file API. Why? Because its exceptions are unreliable (FileNotFoundException can be thrown if you try and open a file to which you have no read access to for instance).
Use that:
final Path path = Paths.get("test1.txt");
try (
final InputStream in = Files.newInputStream(path);
) {
// do something with "in"
} catch (FileSystemException e) {
// fs level error: no permissions, is a directory etc
} catch (IOException e) {
// I/O error
}
You do need to catch FileSystemException before IOException since the former is a subclass of the latter. Among other possible exceptions you can have: AccessDeniedException, FileSystemLoopException, NoSuchFileException etc.

How to best detect certain exceptions?

First of all: StackOverflow tells me that the question is subjective, which it is not.
I have this code:
try {
// Some I/O code that should work fine, but might go weird
// when the programmer fails or other stuff happens...
// It will also throw exceptions that are completely fine,
// such as when the socket is closed and we try to read, etc.
} catch (Exception ex) {
String msg = ex.getMessage();
if (msg != null) {
msg = msg.toLowerCase();
}
if (msg == null || (!msg.equals("pipe closed") &&
!msg.equals("end of stream reached") &&
!msg.equals("stream closed") &&
!msg.equals("connection reset") &&
!msg.equals("socket closed"))) {
// only handle (log etc) exceptions that we did not expect
onUnusualException(ex);
}
throw ex;
}
As you can see my procedure of checking for certain exceptions works, but is VERY dirty. I'm afraid that some VMs might use other strings for the exceptions that should NOT cause the specified method to be called.
What are different solutions I could use for this problem? If I use IOException to check for non-unusual (lol) exceptions, I will not catch any unusual exceptions that derive from it or use it.
For an exception that extends IOException (or another exception), put it in a separate catch statement before the Exception that it extends.
try {
// this might throw exceptions
} catch (FileNotFoundException e) { // this extends IOException
// code
} catch (IOException e) {
// more code
}
In the above example, the code in the first statement will be executed if the exception is an instance of FileNotFoundException. The second one will be executed only if it is an IOException that is not a FileNotFoundException. Using this approach, you can deal with multiple exception types that extend each other.
You can also catch multiple types of exceptions in the same catch statement.
try {
// even more code
} catch (IOException|ArithmeticException e) {
// this will run if an IOException or ArithmeticException is thrown
}
Hope this helps.

Categories