开发者

C++/C# exception throwing

In c++, I am able to throw a bare string as an exception, but in c# I must throw an Exception. What is the c# equivalent to throwing a string i开发者_开发知识库n c++ ?

For example, in c++ I can throw "something bad happened". In c# this would be ..... ?


The question is quite obscure, but I think that the problem is "in C++ you can throw strings; what about C#?"

In C# you throw exceptions in a similar manner to what you do in C++; the main difference is that in C# you can only throw classes derived from System.Exception, while in C++ you can throw any type (although often it's advisable to throw only classes derived from std::exception or from another exception base class; I wouldn't throw plain strings in C++).

Keep in mind that in C# there isn't just System.Exception, but there's a truckload of various derived classes that describe the most common reasons to throw an exception (ArgumentOutOfRangeException, InvalidOperationException, OverflowException, ... just to say some random ones), and this gives you a much better way to express the type of the problem (expressed with the type, which can be discriminated in catch blocks), and you're still able to specify your custom error string by passing it in the constructor. This is much better than just throwing a string, also because, if the exception "bubbles" up to the uppermost catch that more or less can just log the problem and exit, still it can be caught catching a generic System.Exception and still display/log the error string.

Notice that this is possible also in C++, but the ready-made derived exceptions (in <stdexcept>) are much less than the ones provided by the .NET Framework.

Another important difference (coming from C++) is that, while in C++ the stack unwinding that comes from the throw destroys any local object immediately (concept on which is built RAII), in C# the destruction is nondeterministic (it may happen at any moment after the vars that point to them get out of scope); thus it's important to have classes that in such cases must be released immediately implement the IDisposable interface and use the using blocks.


C# only allows to throw objects derived from Exception class. CLR itself allows to throw other types too, so if you really want to you should be able to write method that throws string in some other language or IL directly. You will not be able to catch it as string exception in C# (only as an unknown exception with "catch" without exception type).

Depending on your goals throw new Exception("My string here"); could be enough. EDIT (thanks Neil): but you should create your own exception unless it is one time throw away experiment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜