Why do Java people frequently consume exceptions silently?

前端 未结 28 1614
傲寒
傲寒 2020-11-29 17:50

I never did any serious Java coding before, but I learned the syntax, libraries, and concepts based on my existing skills (Delphi & C#). One thing I hardly understand i

28条回答
  •  [愿得一人]
    2020-11-29 17:55

    If you have a checked exception and you don't want to handle it in a method, you should just have the method throw the exception. Only catch and handle exceptions if you are going to do something useful with it. Just logging it is not very useful in my book as users rarely have time to be reading logs looking for exceptions or know what to do if an exception is thrown.

    While wrapping the exception is an option, I would not suggest you do this unless; you are throwing a different exception to match an exist interface or there really is no way such an exception should be thrown.

    BTW: If you want to re throw a checked exception you can do this with

    try {
       // do something
    } catch (Throwable e) {
       // do something with the exception
       Thread.currentThread().stop(e); // doesn't actually stop the current thread, but throws the exception/error/throwable
    }
    

    Note: if you do this, you should make sure the throws declaration for the method is correct as the compiler is unable to do this for you in this situation.

提交回复
热议问题