Force fatal error if class used in wrong way

Hopefully my question makes sense, and I have Googled several different phrases but it keeps thinking I’m talking about something else.

What I would actually like to do is cause a fatal error inside an if statement. In other words do the same thing that happens if you were to try and change the color.a property of an object, in that case you would have to set color equal to a new Color() object, otherwise Unity would show in red text down the bottom that this is not possible and the application would quit.

Is there a way I can force my class to do this. Say I want a value to always be positive when passed in to the constructor, and if it isn’t positive I want the application to quit and say “Blabla value must be positive” or whatever.

I hope that makes sense, is something like this possible?

Check out the throw statement… Exception-handling statements - throw and try, catch, finally - C# reference | Microsoft Learn

for example in it’s simplest form

throw new System.Exception();

You can use this constructor to specify a custom message

1 Like

In case you don’t want to stop execution but only want to show and error you can use Debug.LogError. Depends on what you want to do and where you want to do it.

1 Like

You generally can’t, and don’t want to, cause a fatal error. Read up on exception handling. In most cases your app should be able to gracefully recover from an exception. Crashing should be a last resort.

1 Like

I sometimes throw exceptions during development, which is what I assumed the OP intentions were. I agree however that this isn’t something you’d want for a released version.

Throwing exceptions is fine. Not catching exceptions that shouldn’t happen is fine too.

Fatal error, that smacks of the blue screen of death from the Windows 95 days…

Edit: To clarify, fatal error is a term used by the operating system when you really, really mess things up. The system must reboot. You don’t want to cause fatal errors.

I assumed the OP incorrectly used the term fatal error when he meant throw an exception, hence my first post. On reflection I should have mentioned that at the time.