aanch
aanch

Reputation: 167

Throw statement outside of catch statement

Is it possible to use throw statement outside of try{} catch{} statement? In my code(Plugin programming in CRM 2011) I just want to show a custom message to the user. If throw doesnot work then how can I do that?

any suggestion?

Upvotes: 3

Views: 8864

Answers (5)

David Spence
David Spence

Reputation: 8079

Yep, as other answers state here, you can throw an exception and prevent any further action in your plugin. However as you are specifically referring to programming with Dynamics CRM plug-ins, I recommended you only ever throw InvalidPluginExecutionException to reflect custom messages to your users as per MSDN guidelines.

You can optionally display a custom error message in a dialog of the Web application by having your plug-in throw an InvalidPluginExecutionException exception with the custom message as the Message property value. It is recommended that plug-ins only pass an InvalidPluginExecutionException back to the platform.

Therefore if you encounter a logical error in your plug-in (eg. Title field is empty) you can:

throw new InvalidPluginExecutionException("Title must not be blank");

Upvotes: 4

Adil
Adil

Reputation: 148140

Yes,

throw new Exception("your message");

or

throw new Exception(objectExtendedFromExceptionClass);

Upvotes: 2

Ravi Gadag
Ravi Gadag

Reputation: 15861

from MSDN : Throwing Exception

Exceptions contain a property named StackTrace. This string contains the name of the methods on the current call stack, together with the file name and line number where the exception was thrown for each method.

yes you can throw exception. like this

throw new Exception("Your Error here!");

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500983

Is it possible to use throw statement outside of try{} catch(){} statement?

Absolutely. The exception will propagate up the stack to the nearest matching catch block. Of course, you will have to have a catch block somewhere doing the right thing... but it needn't be in the same method or even the same class.

Whether an exception is the most appropriate solution here is a different matter, of course - it depends on the context.

Upvotes: 1

glosrob
glosrob

Reputation: 6715

To communicate a message back to a user in a plugin you can simply throw an exception

throw new Exception("Your message here!");

Doesn't have to be in a try/catch block - infact if it was, the message would be suppressed and the user wouldn't see it.

Upvotes: 7

Related Questions