zoukankan      html  css  js  c++  java
  • 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. }

  • 相关阅读:
    【Flask教程02】路由基本定义
    Ubuntu16.04下设置静态IP
    实例讲解虚拟机3种网络模式(桥接、nat、Host-only)
    greenplum单机安装
    GreenPlum 基础操作 入门教程
    repo
    RAW nand clear NAND eMMC
    #运算符、不同的指针类型、数组和指针、指针运算、堆、栈、静态区、只读区、下标VS指针
    LDPC知识点
    宏表达式与函数、#undef、条件编译、
  • 原文地址:https://www.cnblogs.com/bjanzhuo/p/3575958.html
Copyright © 2011-2022 走看看