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

following is a code snippet:

class xxx
{

  public xxx(){}

  try
  {
    throw new Exception(InvalidoperationException);
  }
  catch(Exception x)
  {
  }
  catch(InvalidoperationException x)
  {
  }
}

can anyone tell which exception will raise here and what is the reason behind it.

See Question&Answers more detail:os

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

1 Answer

Wow, lots of problems here. Where to start?

  1. That code won't compile. The try-catch block that you've defined is outside of any method, which is not allowed. You need to move it inside of a method.

  2. Never throw a method that you intend to catch yourself later in the method. That's commonly known as using exceptions for "flow control", which is roundly discouraged. There is a performance cost associated with doing so, and it also makes it very confusing to monitor the exceptions that are being thrown when using a debugger when you have code that's throwing and catching it's own exceptions. Use boolean variables (known as flags) for flow control, if necessary.

  3. Always catch the most derived exception class first. That means you should catch InvalidOperationException first, before trying to catch Exception. You need to reverse the order of your catch blocks in the code that you have.

  4. You should practically never catch System.Exception. The only exceptions that you should catch are those that you explicitly understand and are going to be able to handle. There's virtually no way that you're going to know what went wrong or how to handle it when the only information you have is that a generic exception was thrown.

    Along those same lines, you also should never throw this exception from your own code. Choose a more descriptive exception class that inherits from the base System.Exception class, or create your own by inheriting from the same.


I see that other answers are showing you sample code of what your code should look like, were it to be rewritten. I'm not going to do that because if I rewrote your code to be correct, I'd end up with this:

class Xxx
{
    public Xxx()
    {

    }
}

Not particularly helpful.


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