简体   繁体   中英

Exception priority in try catch blocks

I am making a library so other people can use, I want to make it bulletproof (if thats the correct term). In the code below, I want to check a byte at index 8 of a byte array. If the supplied byte by user of the library is smaller than 9 in length I want to warn user. Consider following code:

    try
    {
        int payloadSizeFromByteArray = Packet[8];
    }
    catch(IndexOutOfRangeException)
    {
        throw new IndexOutOfRangeException("Packet is not valid. Does noe contains byte at index 8 which stores incoming payload length.");
    }
    catch (Exception)
    {
        throw;
    }

ReSharper says the last catch block is redundant. I cant understand, why?! Does it mean there is no chance that last catch block gets reached?

It's redundant because you are not doing anything in the last catch. throw; is what would normally happen.

It's because you're not doing anything with the exception.

You're just "re-throwing" it.

As stated, it is because you are just rethrowing it. I would add two things:

try { ... }
catch( IndexOutOfBoundsException e )
{
 throw new IndexOutOfBoundsException ("your message", e);
}

I would add the original exception

Generally, I would change it so, at the beginning of the function I would add

Contract.Requires( Packet.Length == 8, "your message)" );

This would also add some compile-time checks (Code Contracts) and also avoid a known-before exception.

Its not a precedence issue.

Its redundant because just throwing the same exception is equivalent to the block not being there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM