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?
Related
I have below code. we are using sonar 8.9 version and jdk 11. SonarQube always throw an critical issue
"Define and throw a dedicated exception instead of using a generic one"
try {
String stringPayload = jsonMapper.writeValueAsString(payload);
log.info("Feedzai request: {}"<some object>);
input.setPayload(new StringEntity(stringPayload, APPLICATION_JSON));
} catch (JsonProcessingException e) {
throw new RuntimeException(e.getMessage());
}
I tried to replace catch "RuntimeException" from:
throw new RuntimeException(e.getMessage());
to throw new
RuntimeException(String.format("RuntimeException during processing JSON %s", e.getMessage()),e);
But getting same error.
Could you please some one help me.
Definition of RuntimeExteption:
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
You have two options:
Create a custom exception class
Throw already caught JsonProcessingException
Code for the first option will be:
} catch (JsonProcessingException e) {
//log message somewhere
throw new MyCustomException(e.getMessage());
}
Code for the second option will be:
} catch (JsonProcessingException e) {
//log message somewhere
throw;
}
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.
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.
I am using SonarQube for code quality. I got one issue related to exception handling, which says remove throw clause from finally block.
} catch(Exception e) {
throw new MyException("request failed : ", e);
} finally {
try {
httpClient.close();
} catch (IOException e) {
throw new MyException("failed to close server conn: ", e);
}
}
Based on my understanding above code looks good. If I remove throw clause and suppress exception in finally then caller of this method will not be able to know server's status. I am not sure how we can achieve same functionality without having throw clause.
Your best shot is to use the Automatic Resource Management feature of Java, available since Java 7. If that is for some reason not available to you, then the next best thing is to replicate what that syntactic sugar expands into:
public static void runWithoutMasking() throws MyException {
AutoClose autoClose = new AutoClose();
MyException myException = null;
try {
autoClose.work();
} catch (MyException e) {
myException = e;
throw e;
} finally {
if (myException != null) {
try {
autoClose.close();
} catch (Throwable t) {
myException.addSuppressed(t);
}
} else {
autoClose.close();
}
}
}
Things to note:
your code swallows the original exception from the try block in case closing the resource fails. The original exception is surely more important for diagnostic;
in the ARM idiom above, closing the resource is done differently depending on whether there already was an exception in the try-block. If try completed normally, then the resource is closed outside any try-catch block, naturally propagating any exception.
Generally, methods in the finally block are 'cleanup' codes (Closing the Connection, etc) which the user does not necessarily need to know.
What I do for these exceptions is to absorb the exception, but log the details.
finally{
try{
connection.close();
}catch(SQLException e){
// do nothing and just log the error
LOG.error("Something happened while closing connection. Cause: " + e.getMessage());
}
}
You're getting a warning because this code could potentially throw an exception while dealing with a thrown exception. You can use the try with resource syntax to close the resource automatically. Read more here.
In the case that the "request failed : " exception is thrown and you fail to close the httpclient, the second exception is the one that would bubble up.
I am not sure how we can achieve same functionality without having
throw clause.
You could nest the two try blocks differently to achieve the same result:
HttpClient httpClient = null; // initialize
try {
try {
// do something with httpClient
} catch(Exception e) {
throw new MyException("request failed : ", e);
} finally {
httpClient.close();
}
} catch (IOException e) {
throw new MyException("failed to close server conn: ", e);
}
I have the following code:
try {
DOMConfigurator.configure(url+log4j.xml);
} catch(Exception e) {
e.printStackTrace();
}
And I would expect a FileNotFoundException if the log4j.xml doesn't exist, and then the catch-block would be executed.
But I don't see an exception when the file doesn't exist, why is that?
If you look at the source of DOMConfigurator.doConfigure it looks like it catches Exception and then just logs the error rather than rethrowing it. Therefore the FileNotFoundException will not make it back to your calling code.
try {
...
} catch (Exception e) {
if (e instanceof InterruptedException || e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
// I know this is miserable...
LogLog.error("Could not parse "+ action.toString() + ".", e);
}
To work around this you could preemptively check if the file exists yourself.
Try catching a Throwable instead of an Exception and do a print stack trace. That way you can catch any errors or exceptions and change your code accordingly.
In case you want to disable those messages from log4j, you can set log4j in quiet mode:
LogLog.setQuietMode(true);