Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions in java, rethrown [duplicate]

Tags:

java

In some legacy code I see this, that an overbroad exception is being caught, and then thrown again, Is this a good practice? Does throw e; rethrow the same exception, or create a new one ?

catch (Exception e) {
        StringBuilder sb = new StringBuilder(
                            "Oops. Something went wrong with id: ");
        sb.append(id);
        sb.append(". Exception is: ");
        sb.append(e.toString());
        System.out.println(sb.toString());
        throw e;
}
like image 930
Phoenix Avatar asked Nov 06 '13 22:11

Phoenix


People also ask

Can exception be Rethrown in Java?

If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

Can you Rethrow an exception?

Re-throwing Exceptions When an exception is caught, we can perform some operations, like logging the error, and then re-throw the exception. Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.

Can unchecked exceptions be Rethrown?

A. Only unchecked exceptions can be rethrown.

Can we throws multiple exceptions in Java?

You can't throw two exceptions. I.e. you can't do something like: try { throw new IllegalArgumentException(), new NullPointerException(); } catch (IllegalArgumentException iae) { // ... }


1 Answers

throw e is rethrowing the same exception. At least it preserves the original stacktrace. It's just writing a message to stdout recording some information about what happened, then letting the original exception proceed on its way.

It's not a great practice, it should be enough to log the exceptions in a central place, recording their stacktraces. If you need to add more information (as in the example, where it logs an id), it's better to nest the original exception in a new exception as the cause, then throw the new exception. I would guess this probably occurs in contexts where there is no centralized logging or where exceptions tend to get eaten somewhere.

like image 53
Nathan Hughes Avatar answered Sep 30 '22 15:09

Nathan Hughes