java common practice to rethrow exceptions

New comer to Java may throw exception in the wrong way, and the net outcome of that is very misleading error message, which can cause the user of the libraries very confused. so it is very vital to keep the exception right.

One common case of dealing message is when you are dealing calls from a lower library and you may guard against potential damage from the down-stream and throw domain specific exceptions. that menas you may need to rethrow exception in cases.

But it is easy to get it wrong. by wrong, it often meaning that the original stack is destroyed on the way to propagate to the final consumer. Let 's do a comparison on the following code.

Let 's see the code below

Java代码 复制代码 收藏代码
  1. package Syntax.rethrow;
  2. import java.lang.UnsupportedOperationException;
  3. import java.lang.Exception;
  4. public class Rethrow {
  5. public static void generateException() {
  6. throw new UnsupportedOperationException();
  7. }
  8. public static void rethrowException() throws Exception{
  9. try {
  10. generateException();
  11. } catch (Exception ex) {
  12. // you cannot swallow it
  13. throw new Exception("Caught an exception", ex);
  14. }
  15. }
  16. public static void rethrowExceptionDestroyOriginalCallstack() {
  17. try {
  18. generateException();
  19. } catch (Exception ex) {
  20. throw ex;
  21. }
  22. }
  23. public static void main(String[] args) {
  24. try {
  25. rethrowException();
  26. } catch (Exception ex) {
  27. ex.printStackTrace();
  28. }
  29. System.out.println("-=========================");
  30. try {
  31. rethrowExceptionDestroyOriginalCallstack();
  32. } catch (Exception ex) {
  33. ex.printStackTrace();
  34. }
  35. }
  36. }

原文地址:https://www.cnblogs.com/bjanzhuo/p/3575958.html