How to handle exception without using try catch?

你说的曾经没有我的故事 提交于 2019-12-23 20:30:27

问题


using (SqlConnection con = new SqlConnection())
{
     try
     {
          con.Open();
     }
     catch (Exception ex)
     {
          MessageBox.Show(ex.Message);
     }
}

This works fine. But I want to know can we handle exception without using try catch like some thing if else? or is it mendetory to use try catch


回答1:


There is no other mechanism to handle an exception other than try catch. It sounds like you want something like

if(connection.DidAnErrorOccur)

but that doesn't exist.




回答2:


Only way is to check for all the conditions that would return an error. You should be doing this anyway. Try/catch is expensive. Try catch should be a last resort and there is no way around it for that purpose.




回答3:


The best alternative I can give you is Elmah. http://code.google.com/p/elmah/ It will handle all your uncaught errors and log them. From there I would suggest fixing said errors or catching the specific errors you expect and not just catch any error that might occur. This is best to do so you can fix potential problems and not simply skip over code because an exception occurred.




回答4:


ok, you can implementing de Application_Error in the global.asax, this method is the first line of defense for the errors and is for all the application

http://msdn.microsoft.com/en-us/library/24395wz3%28v=vs.100%29.aspx

for specific page for example default.aspx, you can implementing Page_Error

http://msdn.microsoft.com/en-us/library/ed577840%28v=vs.100%29.aspx

if you are working in mvc so you can implementing the OnException(ExceptionContext filterContext) in every controller that you want, this method is called when an unhandled exception occurs.

http://devproconnections.com/aspnet-mvc/aspnet-mvc-tutorial-handling-errors-and-exceptions

or you can implementing your error atribute

https://www.simple-talk.com/dotnet/asp.net/handling-errors-effectively-in-asp.net-mvc/

For another hand maybe you can use the Assert statement, with this you can evaluate a condition

http://msdn.microsoft.com/en-us/library/ttcc4x86.aspx




回答5:


Tejs' answer is correct, I believe there is no other mechanism to handle errors.

You can, however, handle more specific errors. You can also declare variables outside the try catch to see if it succeeded.

Example:

using (SqlConnection con = new SqlConnection())
{
     bool sqlErrorOccurred;

     try
     {
         con.Open();
         sqlErrorOccurred = false;
     }
     catch (SqlException ex)
     {
          sqlErrorOccurred = true;
     }

     if(sqlErrorOccurred)
     {
         MessageBox.Show("A Sql Exception Occurred");
     }
}



回答6:


The answers above are correct. However, one additional thing to note is that it is possible to set up a global exception handler. This doesn't solve the need for defensive coding as previously mentioned. However, if there are concerns that all exceptions need to be handled (for example, to log the error), then this approach can be very helpful.




回答7:


I'm building a system that uses real-time streaming data, and needs, therefore, to handle errors that could occur when everything else is pretty much idle. The API I'm using passes the errors back through to the program though a method named "error", with the exception attached. This method could then throw the error, but that is problematic, because I can't see how putting my whole program entirely within a try-catch block is a good idea.

So, to get around it, I'll set up an event handler to fire the event in the main part of my program, which can then deal with whatever error gets thrown at that point in time.

For example:

In the main class:

private void Error(object sender, EventArgs e) {

    Exception ex = sender as Exception;

    Console.WriteLine("Error: " + ex); // Or whatever you want to do with the exception

    // You could even add this if you want to then use the try -catch sequence (which 
    // makes the exception easier to parse and also enables you to stop the program
    // with unhandled exceptions if it's something catastrophic:

    try {

        throw ex;
    } catch (put.your.exception.detail.here) {

        // do stuff
   } finally {

       // do other stuff
   }
}

(In the class that receives the error from the API):

class Foo {
    public event EventHandler ThrowError;

    protected virtual void OnError(Object src, EventArgs e) {

        if (ThrowError != null) {

            ThrowError(src, e);
        }
    }

    private virtual void error(Exception e) {

        OnError(e, EventArgs.Empty);
    }
}


来源:https://stackoverflow.com/questions/10304213/how-to-handle-exception-without-using-try-catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!