Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I thought throwing an exception is good practice to let it bubble back up to the UI or somewhere where you log the exception and notify the user about it.

Why does resharper say it is redundant?

try
{
    File.Open("FileNotFound.txt", FileMode.Open);
}
catch
{
    throw;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
737 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because

try {
    File.Open("FileNotFound.txt", FileMode.Open);
} catch {
    throw;
}

is no different than

File.Open("FileNotFound.txt", FileMode.Open);

If the call to File.Open(string, FileMode) fails, then in either sample the exact same exception will find its way up to the UI.

In that catch clause above, you are simply catching and re-throwing an exception without doing anything else, such as logging, rolling back a transaction, wrapping the exception to add additional information to it, or anything at all.

However,

try {
    File.Open("FileNotFound.txt", FileMode.Open);
} catch(Exception ex) {
    GetLogger().LogException(ex);
    throw;
}

would not contain any redundancies and ReSharper should not complain. Likewise,

try {
    File.Open("FileNotFound.txt", FileMode.Open);
} catch(Exception ex) {
    throw new MyApplicationException(
        "I'm sorry, but your preferences file could not be found.", ex);
}

would not be redundant.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...