Is there any valid reason to ever ignore a caught exception

后端 未结 24 1922
南笙
南笙 2020-11-27 15:43

Wow, I just got back a huge project in C# from outsourced developers and while going through my code review my analysis tool revealed bunches of what it considered bad stuff

24条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 16:25

    The following only applies to languages that have checked exceptions, e.g. Java:

    Sometimes a method throws a checked Exception that you know won't happen, e.g. some java APIs expect an encoding name as a string and throw a UnsupportedEncodingException if the given encoding isn't supported. But usually i pass a literal "UTF-8" that i know is supported so I could theoretically write an empty catch there.

    Instead of doing that (empty catch) I usually throw a generic unchecked exception wrapping the "impossible" exception, or I even declare a class ImpossibleException that i throw. Because my theory about that error condition being impossible might be wrong and in that case I wouldn't want the exception to be swallowed.

提交回复
热议问题