bots - C# executes both try and catch -
i've question try catch function in c#. i'm using in discord bot executes both. try , catch. why this? did write wrong or missed little thing?
code:
private void registerkickcommand() { commands.createcommand("kick") .parameter("a", parametertype.unparsed) .alias(new string[] { "k" }) //add alias .addcheck((cm, u, ch) => u.serverpermissions.kickmembers) .do(async (e) => { await e.channel.sendmessage(e.getarg("a")); if (e.message.mentionedusers.firstordefault() == null) { await e.channel.sendmessage(e.user.mention + " that's not valid user!"); } else { try { await e.message.mentionedusers.firstordefault().kick(); await e.channel.sendmessage(e.getarg("kick") + " kicked!"); } catch { await e.channel.sendmessage(e.user.mention + " not have permission kick user!"); } } }); }
so comments pointed out correct behavior. means try
block throws exception hence program processing catch
block well.
one thing though message suggesting reason catch
executed lack of permission. sounds expected, possible within logic of program. in such case instead of try catch block better use flow control if
, e.g.
if(e.message.mentionedusers.firstordefault().haskickpermission()) { // process kick } else { // show message processing not allowed }
the role of try catch handle unexpected. e.g. nullreferenceexception
(which looks may case in code because bit e.message.mentionedusers.firstordefault()
can return null).
also, better handle exceptions should catch instance of exception, , handle accordingly, that:
try { // code } catch(exception ex) { // handle error. e.g. log or display message user. await e.channel.sendmessage("unexpected exception: " + ex.message); }
Comments
Post a Comment