I caught the exception !! Now what?

I started using try catch blocks (a bit late, I know!), But now I'm not sure what to do with the exception as soon as I catch 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 
+69
sql exception exception-handling
Apr 08 '10 at 12:16
source share
16 answers

Rule of thumb for handling exceptions - if you do not know what to do with it, do not understand it.

Correlation in the rule of the thumb for handling exceptions - Handling exceptions at the last crucial moment. If you do not know if this is the last crucial moment, this is not so.

+64
Apr 08 '10 at 12:32
source share

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

You can try again, you can display a message on the screen, write to the log, the possibilities are endless.

As a developer, you cannot predict all possible errors. It is a good idea to have a common catch code, even if you do not know how to fix the error. You can save the database, and one of the 50 database errors may occur, and you will not be able to write code to handle each of them.

You must enter a common catch to make sure that your program is not just crashing, and in some cases just displaying an error and giving them another way is enough. Imagine if the reason was "disk full." You can simply print the exception and let the user try again - they will know what to do and solve the problem themselves.

That is why I disagree with the comment about not processing it if you don't know what to do. You should always contact him, even if he simply displays a message with the error message, because it is infinitely better than "This program has performed an illegal operation and will be closed."

+23
Apr 08 '10 at 12:18
source share

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

  • Cancel transaction
  • Write down the error
  • Notify any user of the application
  • Repeat the operation
  • Delete exception

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

Good article on VB.NET exception handling - Rajesh VS. exception handling in VB.NET

+20
Apr 08 2018-10-10T00:
source share

I see many recommendations not to catch him if you do not know what to do with him. This is just something like law. You should catch exceptions, but maybe not at this level. Using your code as an example, I would 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 no Try / Catch / Finally, no open or closed. The .Fill () function is documented as opening a connection, if required, and the Use block will be absolutely sure that it is closed correctly, even if an exception is thrown.

This gives you the ability to catch exceptions at a higher level; in the user interface or business code calls the function in which your request is executed, and not right here in the request itself. This higher-level code is in a much better position for deciding how to act, what should happen in the log, or show the user an error message.

In fact, this ability of exceptions "bubbles" in your code, which makes them so valuable. If you always catch the exception right where it was thrown, then the exceptions do not add much value beyond the old syntax "On Error Goto X".

+14
Apr 08 '10 at
source share

It depends on what sql really does. It is something:

  • what did the user do? Perhaps create an account or message - then you need to tell the user that something is wrong.
  • what app really? How to clear logs or something like that? Is this fatal? Can the application continue? This is something that can be ignored - perhaps repeated? Should an administrator be advertised?

Start with these questions, they usually lead to answers on how to treat exceptions.

+9
Apr 08 '10 at 12:20
source share

If you did not expect an error (the API says it could happen) and can handle it (there is an obvious step if an exception occurs), you probably want a crash with a lot of noise . This should happen during testing / debugging, so the error can be fixed before the user sees it!

Of course, as commentators note, 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 good error message ("Oh, something went wrong! What were you trying to do?") with submit button ...

Basically, I want to say the following: Do not catch mistakes that you do not know about how to handle! (except for a high-level handler). Crash early and with maximum information. This means that you must register the call stack and other important information, if at all possible for debugging.

+5
Apr 08 '10 at 12:21
source share

If you do not know how to respond to it, do not catch the exception.

Catch it instead in the place where you have the opportunity to process it, and where you know how to proceed later.

+2
Apr 08 '10 at 12:21
source share

Keep in mind that in sections where you feel that you want to use try / catch, you must transfer your Dim statements from the try block. You can assign them values ​​inside the block, but if you define them inside the try block, you will not have access to these variables inside the catch section, since they will not be available at this point.

My standard practice in catch blocks, including attempting to correct an error, if possible, is to write out some kind of logging mechanism, I use information about the key variables that were involved in the section causing the error. This is not necessary, but I found it often helps with debugging problems.

+2
Apr 08 '10 at 12:32
source share

I would suggest that if you do not know what to do with an exception, do not understand it. Too often, coders catch exceptions and simply swallow them whole.

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

Clearly, this is not good, because bad things are happening and no action is being taken. Exclude only exceptions that may be valid!

This suggests that graceful error handling is important. You don’t want your application to crash, do you? You may find ELMAH useful for web applications, and the global exception handler is pretty easy to configure for WinForms or XAML desktop applications.

Combining all this, you can find this strategy useful: 1. catch certain exceptions that, as you know, may occur (DivideByZeroException, SQLException, etc.) and avoid the general Exception; 2. Raise the exception again after handling it. eg.

 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 SQLException? Did you connect to the database? Was this a bad request? You probably don't want to add all the processing logic for this, and besides, what if this is something you did not expect? Therefore, simply handle the exception, if you can, raise it if you are not sure that it is allowed and gracefully handle it at the level (for example, show a message like "Something went wrong, but you could continue working. Details:" [ex.Message] ". Abort or Retry?")

NTN!

John Saunders, thanks for the fix.

+2
Apr 08 2018-10-12T00:
source share

First, if there is no way for the application to handle the exception, you should not catch it ( logging can be done using exception event handlers without catch ).

If there is something you can do, do it. For example, cancel a transaction and report it to the user. It will depend on your application.

+1
Apr 08 2018-10-10T00:
source share

FYI, you do not need to use catch for finally statement.

Sometimes people throw a new exception that is more firendly and adds the original exception as an internal exception.

This is often used to record errors in a file or send email to an operator.

Sometimes, especially with SQL, this can only mean a duplicate key, which means, for example, that you choose a different username that is already accepted - all this applies to your application.

+1
Apr 08 '10 at
source share

I would think about registering that an exception has occurred and notify the user that you were unable to fulfill your request. This assumes that this SQL query is necessary to complete the action that the user is trying to perform.

0
Apr 08 '10 at 12:18
source share

It all depends on the context. Possible options: "Use default data instead of data from the database" and "Display an error message for the user."

0
Apr 08 '10 at 12:18
source share

If you don’t want to do anything about it, you can always just try / finally, and then try / catch / finally

0
Apr 08 2018-10-10T00:
source share

Depending on the type of application, consider either a global logging handler (ie, "Application_Error" for ASP.NET applications) or using a pre-built open source exception handling engine or MSFT.

An exception handling application block as part of Enterprise Library 5.0 — the proposed framework for use.

Besides registering, I agree that exceptions should not be explicitly caught unless you need to do something with them. And the worst mistake is just to “Catch” and then “Throw”, as this will interfere with StackTrace.

0
Jul 18 2018-11-18T00:
source share

Well, it depends in the first place if you make money from your application or not. In my experience, no one (who paid for the application) likes to see it crash and close, instead they prefer a short and explanatory error message and a second chance to continue what they are doing, plus the ability to save / export the changed data. IMO - the best practice is to catch anything that might cause something wrong out of your control, such as I / O operations related to the task network, etc and display the appropriate message to the user. If an exception is thrown due to an error related to logic, it is better not to catch it, as this will help you find and fix the actual error.

Hope this helps.

0
Jun 16 '15 at 1:27
source share



All Articles