How to handle an exception without using try catch?

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

It works great. But I want to know if we can handle the exception without using try catch, like some things if else? or is it a menstruation to usetry catch

+3
source share
7 answers

There is no other mechanism to handle except except try catch. It looks like you want something like

if(connection.DidAnErrorOccur)

but this does not exist.

+5
source

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

+3
source

, , . http://code.google.com/p/elmah/ . , , , . , , , .

+2

Tejs , , .

. try catch, , .

:

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

, , . , , , , . , . , , (, ), .

0

, , , , . API, , , "", . , , , try-catch.

, , , , , .

:

:

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 something catastrophic:

    try {

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

        // do stuff
   } finally {

       // do other stuff
   }
}

( , 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);
    }
}
0

All Articles