I am throwing an exception NotFoundException in my controller to check whether an Object (Building here) is existent in my Database or not and send the 404 HTTP Status like so :
try {
Building building = buildingComponent.getBuildingById(id);
if (building != null) {
return ok(buildingComponent.getBuildingById(id));
} else {
throw new NotFoundException("");
}
}
catch (Exception e) {
// handle exception
e.printStackTrace();
if (e.getClass().getCanonicalName().equals("javassist.NotFoundException")) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
I want to know if throwing and catching the exception like i did (by comparing the canonical name of the exception) is a good exeption handling practise in java spring.
EDIT : i found the solution : it is to catch multiple times (the NotFoundException and others) like this :
catch (NotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
Thank you,
No, this doesn't make a whole lot of sense in multiple ways.
You're throwing the exception just to immediately catch it. If you already know there's an error just go ahead and return an error response:
if (building != null) {
return ok(buildingComponent.getBuildingById(id));
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
There is a built in way to catch exceptions of a specific type. You should specify exceptions being caught from most specific to least specific:
try {
// do something
} catch(NotFoundException e) {
// do some error handling
} catch(Exception e) {
// catch other exceptions
}
In this code There can be two solutions:
No need to throw the exception and handle it by identifying the
exception, You can write like this:
try {
Building building = buildingComponent.getBuildingById(id);
if (building != null) {
return ResponseEntity.ok(buildingComponent.getBuildingById(id));
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
Instead of writing if else in the controller you can throw the exception from the buildingComponent itself and handle the exception later like below.
try {
return ResponseEntity.ok(buildingComponent.getBuildingById(id));
} catch (NotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
To map an exception to a status code they are multiple way to do it with spring:
The simple one is to just let your exception to be propagated and add #ResponseStatus to its definition. In your case #ResponseStatus(HttpStatus.NOT_FOUD) and let ResponseStatusExceptionResolver handle it.
You can create your own HandlerExceptionResolver (more in the doc)
You can use #ExceptionHandler
a full example:
#ControllerAdvice
public class ExceptionHandling {
#ExceptionHandler
public ResponseEntity<String> handle(Exception ex) {
if (ex instanceof NotFoundException) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
}
#Controller
public class MyController {
public ResponseEntity<String> myMethod() {
Building building = buildingComponent.getBuildingById(id);
if (building != null) {
return ok(buildingComponent.getBuildingById(id));
} else {
throw new NotFoundException("");
}
}
}
Make NotFoundException a RuntimeException to avoid throws definition.
More about #ControllerAdvice. You should really look at the documentation you will find everything.
Is it any possible way there to write catch block inside a method and call it from finally when an exception occured in try block
Ex:
try
{
int a=0,b=0;
a=b/0;
}
finally
{
callExceptions();
}
}
public static void callExceptions()
{
catch(Exception e)
{
System.out.println(e);
}
}
catch block must follow a try block. It can't stand alone.
And finally block are made to be after the catch.
You wrote an alone catch inside a finally. That doesn't make sense.
The easiest solution is to pass the exception to the method as a parameter:
public static myMethod() {
try
{
int a=0,b=0;
a=b/0;
}
catch (Exception e)
{
callExceptions(e);
}
finally
{
// do what ever you want or remove this block
}
}
public static void callExceptions(Exception e)
{
System.out.println(e);
}
Ways to uses try/catch/finally
1.- when you want to try to use some method, if everything goes well, will continue else one exception will be thrown on catch block.
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
}
2.- It's the same the first but adding finally block means that the finally block will always be executed independently if some unexpected exception occurs.
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
} finally {
// some logic after try or catch blocks.
}
3.- try and finally blocks are used to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. For example:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
Referencias Official documentation JAVA for try/catch/finally blocks
On your case:
public static myMethod() {
try {
int a=0,b=0;
a=b/0;
} catch (Exception e) {
callException(e);
}
}
public static void callException(Exception e) {
System.out.println(e);
}
This was too long for a comment so sorry it's not a direct answer to your question (as others have pointed out, that's not possible). Assuming what you're trying to do is define a common way to handle your exception logic in one place, Callable might be a way to go. Something like the following might suffice... Although I'm not going to comment on whether any of it is a good idea...
static E callAndHandle(final Callable<E> callable) {
try {
return callable.call();
} catch (final Exception ex) {
System.out.println(ex);
return null;
}
}
static void tryIt() {
final String result = callAndHandle(() -> {
// Thing which might throw an Exception
return "ok";
});
// result == null => there was an error here...
}
Unfortunately Runnable doesn't declare any Exception in the signature, so if you know it always needs to be void and you don't like the return null; or similar hacks, you'd have to define your own interface to pass in.
In my application I have a structure where methods are overloaded. One method does not have Connection as a parameter while the other one has. The one without is only used to create a database connection and then call the other one.
In this example, let's say i call the first method below to create a new user:
#Override
public User handleCreate(User item, boolean silent) throws DAOException {
Connection conn = null;
try {
conn = daoFactory.getConnection();
return handleCreate(conn, item, silent);
} catch (SQLException ex) {
rollback(conn);
close(conn);
throw new DAOException(ex);
} finally {
commit(conn);
close(conn);
}
}
and the other one that has Connection as a parameter:
#Override
public User handleCreate(Connection conn, User item, boolean silent) throws DAOException {
try {
boolean hasError = false;
conn.setAutoCommit(false);
item.setUsername(item.getUsername().trim());
if (item.getId() == 0) { // Not registered user
if (userDAO.existByName(conn, item.getUsername())) { // Username already exist
msg.setErrorMessage(MessageHandler.getMessage("user.create.error.userAlreadyExist"));
hasError = true;
}
if (userDAO.existEmail(conn, item.getEmail())) { // Email already exist
msg.setErrorMessage(MessageHandler.getMessage("user.create.error.emailAlreadyexist"));
hasError = true;
}
if (!hasError) { // No unique violations
Integer id = userDAO.create(conn, item); // Create
item.setId(id);
msg.addMessage(MessageHandler.getMessage("user.create.completeMsg"));
}
} else { // Registered user
msg.setErrorMessage(MessageHandler.getMessage("user.create.error.userAlreadySet"));
}
commit(conn);
close(conn);
return item;
} catch (SQLException ex) {
rollback(conn);
close(conn);
throw new DAOException(ex);
} catch (DAOException ex) {
rollback(conn);
close(conn);
throw ex;
} finally {
commit(conn);
close(conn);
}
}
What I'd like to ask about is what's best practice. I believe I'm overdoing the catching and I'm not sure how to reduce rollback, close etc. in the catch clauses without risking unhandled errors. I also would like to ask if it's best practice to commit and close the transaction/connection where you actually started it - in this case the first method.
Any insight to best practices in this would be much appreciated, or maybe you know another already answered question similar to mine that I haven't found.
If there is an exception, there won't be any changes and you don't have to rollback. You can simply close the connection. Commit at the end is a good practice. If you want best practices, you will have to put a try catch against the close too. And I don't think you can pass connection as a parameter to rollback and commit.
I test exceptions using in java an dobjective-C programs.
In these tests, I see a difference in the way of finally block is reached when an exception is catched and rethrown.
Here my java test :
try {
Boolean bThrow = true;
System.out.println("try : before exception sent");
if (bThrow) {
throw new Exception();
}
System.out.println("try : after sent");
}
catch (Exception e) {
System.out.println("catch, rethrow");
throw e;
}
finally {
System.out.println("finally");
}
which displays :
try: before exception sent
catch, rethrow
finally
And here my objective-c test :
#try {
NSException *myexc = [NSException exceptionWithName:#"exceptionTest" reason:#"exceptionTest" userInfo:nil];
BOOL bThrow = YES;
NSLog(#"try : before exception sent");
if (bThrow) {
#throw myexc;
}
NSLog(#"try : after sent");
}
#catch (Exception *exception) {
NSLog(#"catch, rethrow");
#throw exception;
}
#finally {
NSLog(#"finally");
}
which displays :
try: before exception sent
catch, rethrown
*** Terminating app
Code in finally block is not reached !
Why this difference ?
[EDIT] Sorry, #try ... #try ... #try... was a mistake.
I changed it, but the problem is the same, i can't reach finally block in objective-c test
Your Objective-C code does not have a finally block, just three try blocks. It should look like this:
#try {
NSException *myexc = [NSException exceptionWithName:#"exceptionTest" reason:#"exceptionTest" userInfo:nil];
BOOL bThrow = YES; // Use BOOL or bool
NSLog(#"try : before exception sent");
if (bThrow) {
#throw myexc;
}
NSLog(#"try : after sent");
}
#catch (NSException *e) { // use catch not another try
NSLog(#"catch, rethrow");
#throw e;
}
#finally { // use finally not another try
NSLog(#"finally");
}
OK, i solved my problem.
In my objective-c test, application crashed, that's why finally block was not reached.
If I add a try catch block in the main, now in my function, finally block is reached !
So, I confirm that finally block is still reached whatever an excpetion occurs (and is rethrown) or not).
Is there an elegant way to handle exceptions that are thrown in finally block?
For example:
try {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
finally {
try{
resource.close();
}
catch( Exception ex ) {
// Could not close the resource?
}
}
How do you avoid the try/catch in the finally block?
I usually do it like this:
try {
// Use the resource.
} catch( Exception ex ) {
// Problem with the resource.
} finally {
// Put away the resource.
closeQuietly( resource );
}
Elsewhere:
protected void closeQuietly( Resource resource ) {
try {
if (resource != null) {
resource.close();
}
} catch( Exception ex ) {
log( "Exception during Resource.close()", ex );
}
}
I typically use one of the closeQuietly methods in org.apache.commons.io.IOUtils:
public static void closeQuietly(OutputStream output) {
try {
if (output != null) {
output.close();
}
} catch (IOException ioe) {
// ignore
}
}
If you're using Java 7, and resource implements AutoClosable, you can do this (using InputStream as an example):
try (InputStream resource = getInputStream()) {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
Arguably a bit over the top, but maybe useful if you're letting exceptions bubble up and you can't log anything from within your method (e.g. because it's a library and you'd rather let the calling code handle exceptions and logging):
Resource resource = null;
boolean isSuccess = false;
try {
resource = Resource.create();
resource.use();
// Following line will only run if nothing above threw an exception.
isSuccess = true;
} finally {
if (resource != null) {
if (isSuccess) {
// let close throw the exception so it isn't swallowed.
resource.close();
} else {
try {
resource.close();
} catch (ResourceException ignore) {
// Just swallow this one because you don't want it
// to replace the one that came first (thrown above).
}
}
}
}
UPDATE: I looked into this a bit more and found a great blog post from someone who has clearly thought about this more than me: http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html He goes one step further and combines the two exceptions into one, which I could see being useful in some cases.
As of Java 7 you no longer need to explicitly close resources in a finally block instead you can use try-with-resources syntax. The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Assume the following code:
try( Connection con = null;
Statement stmt = con.createStatement();
Result rs= stmt.executeQuery(QUERY);)
{
count = rs.getInt(1);
}
If any exception happens the close method will be called on each of these three resources in opposite order in which they were created. It means the close method would be called first for ResultSetm then the Statement and at the end for the Connection object.
It's also important to know that any exceptions that occur when the close methods is automatically called are suppressed. These suppressed exceptions can be retrieved by getsuppressed() method defined in the Throwable class.
Source: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Ignoring exceptions which occur in a 'finally' block is generally a bad idea unless one knows what those exceptions will be and what conditions they will represent. In the normal try/finally usage pattern, the try block places things into a state the outside code won't be expecting, and the finally block restores those things' state to what the outside code expects. Outside code which catches an exception will generally expect that, despite the exception, everything has been restored to a normal state. For example, suppose some code starts a transaction and then tries to add two records; the "finally" block performs a "rollback if not committed" operation. A caller might be prepared for an exception to occur during the execution of the second "add" operation, and may expect that if it catches such an exception, the database will be in the state it was before either operation was attempted. If, however, a second exception occurs during the rollback, bad things could happen if the caller makes any assumptions about the database state. The rollback failure represents a major crisis--one which should not be caught by code expecting a mere "Failed to add record" exception.
My personal inclination would be to have a finally method catch exceptions that occur and wrap them in a "CleanupFailedException", recognizing that such failure represents a major problem and such an exception should not be caught lightly.
One solution, if the two Exceptions are two different classes
try {
...
}
catch(package1.Exception err)
{
...
}
catch(package2.Exception err)
{
...
}
finally
{
}
But sometimes you cannot avoid this second try-catch. e.g. for closing a stream
InputStream in=null;
try
{
in= new FileInputStream("File.txt");
(..)// do something that might throw an exception during the analysis of the file, e.g. a SQL error
}
catch(SQLException err)
{
//handle exception
}
finally
{
//at the end, we close the file
if(in!=null) try { in.close();} catch(IOException err) { /* ignore */ }
}
Why do you want to avoid the additional block? Since the finally block contains "normal" operations which may throw an exception AND you want the finally block to run completely you HAVE to catch exceptions.
If you don't expect the finally block to throw an exception and you don't know how to handle the exception anyway (you would just dump stack trace) let the exception bubble up the call stack (remove the try-catch from the finally block).
If you want to reduce typing you could implement a "global" outer try-catch block, which will catch all exceptions thrown in finally blocks:
try {
try {
...
} catch (Exception ex) {
...
} finally {
...
}
try {
...
} catch (Exception ex) {
...
} finally {
...
}
try {
...
} catch (Exception ex) {
...
} finally {
...
}
} catch (Exception ex) {
...
}
After lots of consideration, I find the following code best:
MyResource resource = null;
try {
resource = new MyResource();
resource.doSomethingFancy();
resource.close();
resource = null;
} finally {
closeQuietly(resource)
}
void closeQuietly(MyResource a) {
if (a!=null)
try {
a.close();
} catch (Exception e) {
//ignore
}
}
That code guarantees following:
The resource is freed when the code finished
Exceptions thrown when closing the resource are not consumed without processing them.
The code does not try to close the resource twice, no unnecessary exception will be created.
If you can you should test to avoid the error condition to begin with.
try{...}
catch(NullArgumentException nae){...}
finally
{
//or if resource had some useful function that tells you its open use that
if (resource != null)
{
resource.Close();
resource = null;//just to be explicit about it was closed
}
}
Also you should probably only be catching exceptions that you can recover from, if you can't recover then let it propagate to the top level of your program. If you can't test for an error condition that you will have to surround your code with a try catch block like you already have done (although I would recommend still catching specific, expected errors).
You could refactor this into another method ...
public void RealDoSuff()
{
try
{ DoStuff(); }
catch
{ // resource.close failed or something really weird is going on
// like an OutOfMemoryException
}
}
private void DoStuff()
{
try
{}
catch
{
}
finally
{
if (resource != null)
{
resource.close();
}
}
}
I usually do this:
MyResource r = null;
try {
// use resource
} finally {
if( r != null ) try {
r.close();
} catch( ThatSpecificExceptionOnClose teoc ){}
}
Rationale: If I'm done with the resource and the only problem I have is closing it, there is not much I can do about it. It doesn't make sense either to kill the whole thread if I'm done with the resource anyway.
This is one of the cases when at least for me, it is safe to ignore that checked exception.
To this day I haven't had any problem using this idiom.
try {
final Resource resource = acquire();
try {
use(resource);
} finally {
resource.release();
}
} catch (ResourceException exx) {
... sensible code ...
}
Job done. No null tests. Single catch, include acquire and release exceptions. Of course you can use the Execute Around idiom and only have to write it once for each resource type.
Changing Resource from best answer to Closeable
Streams implements Closeable Thus you can reuse the method for all streams
protected void closeQuietly(Closeable resource) {
if (resource == null)
return;
try {
resource.close();
} catch (IOException e) {
//log the exception
}
}
I encountered a situation similar where I couldn't use try with resources but I also wanted to handle the exception coming from the close, not just log and ignore it like closeQuietly mechanism do. in my case I'm not actually dealing with an output stream, so the failure on close is of more interest than a simple stream.
IOException ioException = null;
try {
outputStream.write("Something");
outputStream.flush();
} catch (IOException e) {
throw new ExportException("Unable to write to response stream", e);
}
finally {
try {
outputStream.close();
} catch (IOException e) {
ioException = e;
}
}
if (ioException != null) {
throw new ExportException("Unable to close outputstream", ioException);
}