Amit
Amit

Reputation: 22076

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.

Upvotes: 7

Views: 26115

Answers (8)

nsf-coding
nsf-coding

Reputation: 66

In .NET core 3.1 (or before?), You could set up a global catcher for unhandled exceptions. However, the APP won't continue to run after that.

Here is an example:

https://learn.microsoft.com/en-us/dotnet/api/system.appdomain.unhandledexception?redirectedfrom=MSDN&view=netcore-3.1

Upvotes: 0

Fermin Pitol
Fermin Pitol

Reputation: 486

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

Upvotes: 4

Steven C. Britton
Steven C. Britton

Reputation: 482

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);
    }
}

Upvotes: 0

CosmicFreddy
CosmicFreddy

Reputation: 3

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.

Upvotes: 0

John Sykor
John Sykor

Reputation: 727

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.

Upvotes: 2

Scen
Scen

Reputation: 1720

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");
     }
}

Upvotes: 1

KingOfHypocrites
KingOfHypocrites

Reputation: 9537

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.

Upvotes: 3

Tejs
Tejs

Reputation: 41246

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.

Upvotes: 6

Related Questions