简体   繁体   中英

try catch block to display Error message

I have a doubt about Try Catch blocks. If I get an error in Try block then it will redirect to Catch block as per to the rule. So can I set visible = true to my label into catch block .

ie lblError.visible=true;

Is it correct as per coding standards? I am new to developing.

例如,您可以在catch块中将输入元素的可见性设置为false,并显示错误面板。

That's right , whats wrong in that? Maybe you are not comfortable of visibling and setting lblError in catch block as try..catch can be appeared many places in your code, if it is, you can wrap up those two lines in a function and call it from every catch block.

You can also throw exception from catch block and handle them all at one place at session level or application level and redirect to one default error page where you can get the last error occurred and show user friendly message as per it.

You can also enable CustomErrors section in web.config and redirect to one specific page on any error occurred in the session.

try
{
  //statements;
}
catch (Exception ex)
{
  ShowError(ex);
}

void ShowError(Exception ex)
{
   //Log or Email error first
   LogOrEmailError(ex);

   // you can write user friendly message based on the exception provided or a generic error message.
   lblError.Visible = true;
   lblError.Text = GetUserFriendlyErrorMessage(ex); // or throw; if you are planing to handle error in global.ascx or through CustomErrors in web.config
}

Yes very much. You can write normal coding lines in catch block.

Catch block gives developer to recover the damage done by the error thrown in try block.

So You can write down any code that should run if an error appear in try block. ie Error logging

Yes, you can write any code inside a catch block, even return from method. The one moment is you must use finaly{} block to release any resource that you use in the method where exception was throwed, (for example, you use database connection).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM