I've caught an exception!! Now what?

Sqlvb.netException

Sql Problem Overview


I've started using try-catch blocks (a bit late, I know!), but now I'm not sure what to do with the exception once I've caught it. What should I do?

Try
    connection.Open()
    Dim sqlCmd As New SqlCommand("do some SQL", connection)
    Dim sqlDa As New SqlDataAdapter(sqlCmd)
    sqlDa.Fill(dt)
Catch ex As SQLException
    ' Ahhhh, what to do now!!!?
Finally
    connection.Close()
End Try

Sql Solutions


Solution 1 - Sql

Rule of thumb for exception handling--If you don't know what to do with it, don't catch it.

Corollary to the rule of thumb for exception handling--Handle exceptions at the last responsible moment. If you don't know if this is the last responsible moment, it isn't.

Solution 2 - Sql

What do you want to do? It depends entirely on your application.

You could have it retry, you could display a message box to the screen, write to a log, the possibilities are endless.

As a developer, you can't predict every possible error. It's a good idea to have a generic catch code in even if you don't know how to fix the error. You could be saving to a database, and one of 50 database errors might occur, and you won't be able to write code to handle every single one.

You should put a generic catch in to make sure your program doesn't simply crash, and in some cases simply displaying the error and letting them have another go is enough. Imagine if the cause was 'disk is full'. You could merely print out the exception, and let the user try again - they'd know what to do, and solve the problem themselves.

This is why I disagree with the comment about not handling it if you don't know what to do. You should always handle it, even if it is just to display a message box saying 'Error' because it's infinitely better than "This program has performed an illegal operation and will be closed."

Solution 3 - Sql

It depends on your business logic, but you may want to do one or more of the following.

  • Rollback your transaction
  • Log the error
  • Alert any user of the application
  • Retry the operation
  • Rethrow the exception

You may also wish to check if the exception is of a type you can handle before one of the above.

A good article on VB.NET exception handling is Exception Handling in VB.NET by Rajesh VS.

Solution 4 - Sql

I see a lot of recommendations not to catch it if you don't know what to do with it. That's only sort of right. You should be catching exceptions, but maybe not at this level. Using your code for an example, I'd write it more like this:

Using connection As New SqlConnection("connection string here"), _
      sqlCmd As New SqlCommand("do some SQL", connection), _
      sqlDa As New SqlDataAdapter(sqlCmd)

    sqlDa.Fill(dt)
End Using

Not only is there no Try/Catch/Finally, there's no open or close. The .Fill() function is documented as opening the connection if required, and the Using block will make absolutely certain it's closed correctly, even if an exception is thrown.

This leaves you free to catch exceptions at a higher level — in the UI or business code then calls the function where your query runs, rather than right here at the query itself. This higher-level code is in a much better position to make decisions about how to proceed, what logging needs to happen or show a better error message to the user.

In fact, it's this ability for exceptions to "bubble up" in your code that makes them so valuable. If you always catch an exception right there where it's thrown, then exceptions aren't adding much value beyond the vb's old "On Error Goto X" syntax.

Solution 5 - Sql

It depends on what the SQL does really. Is it something:

  • that the user did? Perhaps create an account or a message - then you need to inform the user that something is wrong
  • that the application does naturally? Like cleaning up logs or something similar? Is it fatal? Can the application go on? Is it something that can be ignored - perhaps retried? Should the administrator be announced?

Start with these questions, they will usually lead to answers about how to treat exceptions

Solution 6 - Sql

Unless you were expecting the error (the API says it can occurr) and can handle it (there is an obvious step to take if the exception occurrs), you probably want to crash with a lot of noise. This should happen during testing / debugging, so that the bug can get fixed before the user sees it!

Of course, as commenters have pointed out, the user should never really see all this noise. A high-level try/catch or some other method (EMLAH, I hear for .net web projects) can be used to show the user a nice error message ("Oops! Something went wrong! What on earth were you trying to do?") with a submit button...

So basically, my point is this: Do not catch errors you don't know how to handle! (except for the high-level handler). Crash early and with as much information as possible. This means you should log the call stack and other vital information if at all possible for debugging.

Solution 7 - Sql

If don't know how to react to it, don't catch the exception.

Catch it instead in a place where you have the possibility to handle it and where you know how to continue execution afterwards.

Solution 8 - Sql

One thing to keep in mind is that in sections where you feel you do want to use a try/catch, you should move your Dim statements out of the try block. You can assign them values inside the block, but if you define them inside the try block, you won't have access to those variables inside the catch section as they will be out of scope at that point.

My standard practice in catch blocks, including trying to remediate the error if possible, is to write out to whatever logging mechanism I am using information about key variables that were involved in the section causing the error. It's not necessary, but I've found it often helps with debugging problems.

Solution 9 - Sql

I'd like to suggest to you that if you do not know what to do with an exception, do not catch it. Too often, coders catch exceptions and just swallow them whole.

catch (Exception ex)
{
  /* I don't know what to do.. *gulp!* */
}

Clearly this isn't good, because bad things are happening, and no action is being taken. Only catch exceptions that are actionable!

That said, graceful error handling is important. Don't want your app to crash, right? You may find ELMAH useful for web applications, and a global exception handler is pretty easy to set up for WinForms or XAML desktop apps.

Putting all that together, you might find this strategy useful: 1. catch specific exceptions that you know might occur (DivideByZeroException, SQLException, etc.) and steer away from the generic catch-all Exception; 2. re-raise the exception after you handle it. e.g.

catch (SQLException ex)
{
  /* TODO: Log the error somewhere other than the database... */
  throw; // Rethrow while preserving the stack trace.
}

What can you really do with an SQLException? Did the database connection disappear? Was it a bad query? You probably don't want to add all the handling logic for that, and besides, what if it's something you didn't expect? So just handle the exception if you can, re-raise it unless you're certain it's resolved, and gracefully handle it at a global level (e.g. Show a message like "Something went wrong, but you might be able to continue working. Detailed info: '[ex.Message]'. Abort or Retry?")

HTH!

John Saunders, thanks for the correction.

Solution 10 - Sql

First, if there is no way for your application to handle the exception then you shouldn't catch it in the first place (logging can be done via exception event handlers without catching).

If there is something you can do then do that. For example, roll back the transaction and report it failed to the user. This is going to depend on your application.

Solution 11 - Sql

FYI, you don't have to use the catch to have a finally statement.

Sometimes people throw a new exception that is more firendly and add the original exception as the inner exception.

Often this is used to log the error to a file or send an email to an operator.

Sometimes, especially with SQL, it may just mean a duplicate key which means, for example, please choose another username, that one is already taken - it's all down to your application.

Solution 12 - Sql

I would consider logging that the exception took place and notify the user that you were unable to complete their request. This assumes that this SQL request is necessary to completion of the action the user is attempting to perform.

Solution 13 - Sql

It depends entirely on context. Possible options include "Use default data instead of data from the database" and "Display an error message to the user".

Solution 14 - Sql

If you don't want to do anything with it, you can always just do try/finally rather then try/catch/finally

Solution 15 - Sql

Depending on the type of application, consider either a global logging handler (i.e. 'Application_Error' for ASP.NET applications) or using a pre-built open source or MSFT provided exception handling framework.

The Exception Handling Application Block as part of the Enterprise Library 5.0 is a suggested framework to use.

Aside from logging, I agree that exceptions need not be explicitly caught unless you need to do something meaningful with them. And the worst mistake is just to 'Catch' and then 'Throw' again as this messes the StackTrace up.

Solution 16 - Sql

Well, That depends primarily if you are making money from your application or not. By my experience, nobody (who paid for an application) likes to see it crashing and closing, instead they prefer a short and explanatory message about the error and a second chance to continue whatever they were doing plus a chance to save/export their modified data. IMO a best practice is to catch everything that can cause something wrong out of your control, like I/O operations, networking related tasks, e.t.c. and display a relevant message to the user. In case that an exception is thrown due to a logic related error is better not to catch it since this will help you to find and correct the actual error.

Hope this helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniamjonesyView Question on Stackoverflow
Solution 1 - Sqluser1228View Answer on Stackoverflow
Solution 2 - SqlNibblyPigView Answer on Stackoverflow
Solution 3 - SqlColin PickardView Answer on Stackoverflow
Solution 4 - SqlJoel CoehoornView Answer on Stackoverflow
Solution 5 - SqllauraView Answer on Stackoverflow
Solution 6 - SqlDaren ThomasView Answer on Stackoverflow
Solution 7 - SqlsthView Answer on Stackoverflow
Solution 8 - SqlBBlakeView Answer on Stackoverflow
Solution 9 - SqlTodd SprangView Answer on Stackoverflow
Solution 10 - Sqljk.View Answer on Stackoverflow
Solution 11 - SqlJames WestgateView Answer on Stackoverflow
Solution 12 - SqlAdam DriscollView Answer on Stackoverflow
Solution 13 - SqlQuentinView Answer on Stackoverflow
Solution 14 - SqlMatt BriggsView Answer on Stackoverflow
Solution 15 - SqlatconwayView Answer on Stackoverflow
Solution 16 - SqlChD ComputersView Answer on Stackoverflow