Is there any valid reason to ever ignore a caught exception

后端 未结 24 1956
南笙
南笙 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:26

    To take an example from the Java world where it's OK to ignore an exception:

    String foo="foobar";
    byte[] foobytes;
    
    try
    {
        foobytes=foo.getBytes("UTF-8");
    }
    catch (UnsupportedEncodingException uee)
    {
        // This is guaranteed by the Java Language Specification not to occur, 
        // since every Java implementation is required to support UTF-8.
    }
    

    That said, even in situations like this, I'll often instead use

    ...
    catch (UnsupportedEncodingException uee)
    {
        // This is guaranteed by the Java Language Specification not to occur, 
        // since every Java implementation is required to support UTF-8.
        uee.printStackTrace();
    }
    

    If the virtual machine is going to be mad/spec-breaking, there's little I can do about it, but with the stack trace, I at least get to notice when it started its descent into madness...

提交回复
热议问题