Simon
Simon

Reputation: 34840

How to throw/cause a non .net exception in c#?

So for testing purposes I want to throw an exception that does not derive from Exception.

Any way to do this in c#, perhaps by calling some low level API, that will reliable cause this to happen?

Or do I need to write some c++?

Upvotes: 2

Views: 956

Answers (3)

riQQ
riQQ

Reputation: 12733

You can throw objects that don't derive from the Exception type in C++/CLI

See the example code from https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.runtimewrappedexception?view=netframework-4.8#examples

using namespace System;
using namespace System::Runtime::CompilerServices;

[assembly:RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)]; 

void run()
{
    try
    {
        throw gcnew String("This is a string");

    }
    catch(RuntimeWrappedException^ e)
    {
        Console::WriteLine("RuntimeWrappedException caught!");
    }
}

int main()
{
    run();

    return 0;
}

Upvotes: 0

JohnC
JohnC

Reputation: 842

C# can only throw exceptions derived from System.Exception. That said, the CLR permits throwing any object. So you could do what you want to do by writing a class library in CIL (Edit: this is not as difficult as it sounds) and coding a method to throw a object not derived from Exception. I don't know how C# would perceive that object though.

Upvotes: 1

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

From Handling and Throwing Exceptions:

How the Runtime Manages Exceptions

The runtime uses an exception-handling model based on exception objects and protected blocks of code. An Exception object is created to represent an exception when it occurs. The runtime creates an exception information table for each executable. Each method of the executable has an associated array of exception-handling information (which can be empty) in the exception information table. Each entry in the array describes a protected block of code, any exception filters associated with that code, and any exception handlers (catch statements). This exception table is extremely efficient and does not cause any performance penalty in processor time or in memory use when an exception does not occur. You use resources only when an exception occurs.

Basically, you cant get around properly inheriting from Exception. Even throwing exceptions via C++ will cause the exception to propogate to managed code (if it does) to some form of exception object which inherits from Exception

Because execution threads routinely traverse managed and unmanaged blocks of code, the runtime can throw or catch exceptions in either managed or unmanaged code. Unmanaged code can include both C++-style SEH Exceptions and COM-based HRESULTS.

Upvotes: 0

Related Questions