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

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c# - Will CLR handle both CLS-Complaint and non-CLS complaint exceptions?

Just for my clarification :

Can i throw both CLS-Complaint and non-CLS complaint exceptions in .NET Framework ?.I am using C# 3.0.

When i catch exception

catch(Exception ex)
{

}
  • Will it catch only CLS-Complaint exceptions?.
  • What is the use of RuntimeWrappedException class (can i have a simple example?).
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
  1. Yes, you can throw non-CLS compliant exceptions in the .NET Framework, as long as you use a language that allows it, e.g. C++.
  2. No, you cannot throw non-CLS compliant exceptions in C#.
  3. No, it will catch all exceptions, since any non-CLS compliant exception will be wrapped in a RuntimeWrappedException, which derives from Exception.
  4. You do not throw a RuntimeWrappedException, the CLR does. MSDN has a detailed description, which I quote here:

    Some languages, such as C++, allow you to throw exceptions of any managed type. Other languages, such as Microsoft C# and Visual Basic, require that every thrown exception be derived from the Exception class. To maintain compatibility between languages, the common language runtime (CLR) wraps objects that do not derive from Exception in a RuntimeWrappedException object.

If you want to treat CLS and non-CLS exceptions differently, just catch them in the right order:

try {
    // some code
catch(RuntimeWrappedException ex) {
    // non-CLS exceptions
catch(Exception ex) {
    // CLS exceptions
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...