Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exception without using try catch?

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.

like image 686
jams Avatar asked Apr 24 '12 18:04

jams


2 Answers

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.

like image 122
Tejs Avatar answered Sep 19 '22 01:09

Tejs


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

like image 23
Fermin Pitol Avatar answered Sep 21 '22 01:09

Fermin Pitol