How to make C# application crash
Asked Answered
C

14

11

I want to test if my application crash dump can be debugged. But firstly, I need to generate a crash dump of my application. I'm using C# to code my app, and have tried with many exceptions and unsafe code etc. but don't get it.

Thanks!

Edit: Sorry, Just forgot something, I'm making the application with Unity3D, which handles exceptions for me automatically.

Edit 2: Thanks all for your answers. I've tested your suggestions in a standard C# application and it all works fine, but not in my Unity3D application (written with C#). It seems like Unity3D requires more effort to cause a crash, I might email Unity3D to get a answer. I will post here if I get it. Cheers!

Cindiecindra answered 1/8, 2013 at 14:23 Comment(11)
Congrats, you seem to be the most professional programmer!Forearm
how about int x = 0; double blah = 5/x;Anselmo
object obj = null; obj.ToString();Drear
A crash simply occurs when an unmanaged exception is thrown at runtime. There's nothing magic behind it. Maybe the problem is that your code isn't working correctly, and that's why you're not having any log.Drachm
What kind of application it is?Mishandle
Throw an exception forcefully.Bolyard
int[] x = {0}; int blah = x[2];Anselmo
throw new Exception(); ... ?Ethmoid
Partially unseat a DIMM on the motherboard?Chaudoin
Perhaps this will help: #1134548Aeriela
This seems like a poorly researched questionDoorplate
Y
23

The following will provide an unhandled exception and will ask for you to choose a debugger:

System.Diagnostics.Debugger.Launch()
Yount answered 1/8, 2013 at 14:25 Comment(3)
Although the question was a silly one but this answer definitely was the opposite, +1.Meld
sorry, I try, but get "NotImplementedException: The requested feature is not implemented"Cindiecindra
Since you say you are developing in Unity3D, this might not be an option, sorry...Yount
A
19

StackOverflowException is a badass:

void PerformOverflow()
{
  PerformOverflow();
}

Usage:

PerformOverflow();
Amorita answered 18/6, 2015 at 11:22 Comment(0)
K
12

Throw an exception :)

throw new Exception("Your exception here!");
Keramics answered 1/8, 2013 at 14:26 Comment(3)
sorry,I have try throwing an exception, but that doesn't crash my application.Cindiecindra
sorry, I lost something: I use Unity3d, and it handles all exceptions, just show me the exceptions in the output file. thanksCindiecindra
This is not a CRASH. A crash can only occur from native code that crashes, or calls into RaiseException Win32 API.Doubloon
L
11

For C# in Unity3D

There is UnityEngine.Diagnostics.Utils.ForceCrash (in Unity 2018.3)

This can be used with one of the following ForcedCrashCategory enum parameter:

AccessViolation

Cause a crash by performing an invalid memory access.The invalid memory access is performed on each platform as follows:

FatalError

Cause a crash using Unity's native fatal error implementation.

Abort

Cause a crash by calling the abort() function.

PureVirtualFunction

Cause a crash by calling a pure virtual function to raise an exception.


For older versions of Unity:

UnityEngine.Application.ForceCrash(int mode)

For even older versions (Unity 5):

UnityEngine.Application.CommitSuicide(int mode)

From my experience, mode 0 causes a "unity handled" crash (where the Unity crash dialog appears), and mode 2 causes a "hard" crash where the Windows error dialog appears.

This seems consistent with this post by Smilediver on mode:

0 - will simulate crash, 1 - will simulate a fatal error that Unity has caught, 2 - will call abort().

(These methods are not documented as they were intended for Unity's internal use. They may also be marked [Obsolete] depending on your Unity version.)

Loyce answered 16/8, 2019 at 16:22 Comment(0)
W
8

Well. The only good 100% way actualy crash CLR is to inject a native exception into the managed world.

Calling the Kernel32.dll's RaiseException() directly will immediately crash ANY C# application, and Unity Editor as well.

[DllImport("kernel32.dll")]
static extern void RaiseException(uint dwExceptionCode, uint dwExceptionFlags,  uint nNumberOfArguments, IntPtr lpArguments);

void start()
{
    RaiseException(13, 0, 0, new IntPtr(1));
}

Happy crashing. Please note that in order to debug native and managed, you will need two instances of Visual Studio running. If you are developing native P/INVOKE plugin, set up it that Visual Studio Instance 1 is native debugger and uses Unity or your C# program as a Host program, and you attach to the Host program from another Visual Studio Instance.

Wilkins answered 22/8, 2016 at 22:12 Comment(3)
you do not need to SCREAM any time you want to highlight stuff. Use italic or bold works better... Just saying because it is annoying to see you scream even in comments...Forearm
It's an old habit like in when you always work with legalese to highlight stuff and important sentences, you use caps-lock...Doubloon
Thanks, this worked perfectly for me. The code generates a Unity-managed application crash.Darnel
O
7

Another option is to call

System.Environment.FailFast("Error happened")
Obumbrate answered 16/10, 2019 at 7:52 Comment(3)
Worked and has the benefit of being the intended method provided by system library.Schiller
Worked for testing crashing an ASP.NET Core application as well (most of the higher rated options didn't seem to do the trick) - thanks!Discordant
This will put exception details in the Event Log, possibly being reported to Microsoft via Windows Error Reporting (WER). Maybe desired, maybe not.Suburban
W
6

A surefire way to do it is as follows:

ThreadPool.QueueUserWorkItem(new WaitCallback(ignored => 
{
   throw new Exception();
}));

All the others can be handled by the top level ApplicationDomain.OnUnhandledException and the like.

This one will kill it dead (assuming .NET 2.0+, and not using 'legacyUnhandledExceptionPolicy': http://msdn.microsoft.com/en-us/library/ms228965.aspx).

Woodie answered 2/8, 2013 at 14:16 Comment(4)
It seems unity3d application ignore the exception directly(not handle it like others), and has no any feedback.Cindiecindra
If you want even less code... ThreadPool.QueueUserWorkItem(ignored => throw new Exception());Backup
Even less ThreadPool.QueueUserWorkItem(_ => throw new Exception());Chromatism
Note that Unity3d will log this exception as long as UnityEngineApplication.logMessageReceivedThreaded is used (rather than logMessageReceived)Loyce
C
0

None of the answers crashed my app the way I was looking for. So here is the approach that worked for me.

    private void Form1_Load(object sender, EventArgs e)
    {
        object p = 0;
        IntPtr pnt = (IntPtr)0x123456789;
        Marshal.StructureToPtr(p, pnt, false);
    }
Chenay answered 15/3, 2016 at 8:48 Comment(1)
Crash is not guaranteed using this.Doubloon
S
0
  public void Loop()
  {
      Loop();
  }
  //call this
  Loop();
Stickler answered 15/3, 2016 at 9:11 Comment(0)
M
0

I think there was a code in earlier unity versions like

Application.commitSuicide(number Input); 

Now it is replaced by

Application.ForceCrash(number input); 

Till this point, I dont know what different numbers do in number input, but for me,

Application.ForceCrash(1); 

does the job.

Magnanimity answered 9/5, 2021 at 16:31 Comment(0)
E
0

you could also divide by zero,

z = 0; 
int divide = 1 / x;
Ellie answered 23/8, 2021 at 20:12 Comment(0)
A
-1
 int[] x = {0};
 int blah = x[2];

will cause an exception just as well

Anselmo answered 1/8, 2013 at 14:28 Comment(3)
sorry,I have try throwing an exception, but that doesn't crash my applicationCindiecindra
sorry, I lost something: I use Unity3d, and it handles all exceptions, just show me the exceptions in the output file. thanksCindiecindra
this won't always crash, since hadling operation of reading out side of boundes is not standard specified. Your program could crash when OS detects process trying to access other process memory, but if you don't go beyond memory assigned to your process you will just read random memory placesBryanbryana
G
-1

It's easy enough to reproduce if you try to transform a null game object. For example, like this:

public static GameObject gameObjectCrash;
public void GenerateCrash()
{
    gameObjectCrash.transform.rotation = Quaternion.Euler(90, 0, 0);
}
Grasmere answered 7/3, 2019 at 12:59 Comment(0)
W
-3

Use below code to close the application.

Environment.Exit(1);    

Exit needs a parameter called exitcode. If exitcode=0 means there was no error. Supply a non-zero exit code to to reflect an error.

Wiebmer answered 27/2, 2015 at 6:51 Comment(1)
This is CLOSING, not a CrashDoubloon

© 2022 - 2024 — McMap. All rights reserved.