When should Throwable be used instead of new Exception?

前端 未结 12 1254
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 08:21

Given: Throwable is Exception\'s superclass.

When I read texts on writing your own \'exceptions\', I see examples of Throwable

12条回答
  •  佛祖请我去吃肉
    2020-11-28 09:21

    You should not really catch an exception and throw a new one as general as "new Exception".

    Instead, if you wish to bubble up the exception just do the following:

    try {
        // Do some stuff here
    }
    catch (DivideByZeroException e) {
        System.out.println("Can't divide by Zero!"); 
    } 
    catch (IndexOutOfRangeException e) { 
        // catch the exception 
        System.out.println("No matching element found.");
    }
    catch (Throwable e) {
        throw e; // rethrow the exception/error that occurred
    }
    

    It is not good practise, I believe, to catch an exception and throw a new exception instead of the one that was raised to your code block, unless you raise a useful custom exception that provides enough context to elude to the cause of the original exception.

提交回复
热议问题