Is there a good reason to ignore the exception

Wow, I just returned a huge C # project from third-party developers, and while looking at my code review, my analysis tool found bundles of what it considered bad. One of the most annoying posts was:

Exceptions.DontSwallowErrorsCatchingNonspecificExceptionsRule : 2106 defects 

The developers assure me that they have a good reason for all empty catch blocks, which sometimes try with empty catch blocks to ignore useless exceptions and prevent the application from crashing. I feel like a cop and a complete BS. Some of the examples that I really looked for were database calls, where the record was stored in the database, in which case, if the exception was ignored, the user would return a hint, assuming that everything is in order, and continue their work. In fact, their work was never saved. I think this is an absolutely terrible mistake. In this case, they are completely wrong when throwing this code in an attempt with an empty catch block. But my question is: "Is it EVERY acceptable in ANY situation?" I think not, but, as you know, I was mistaken.

+49
c # exception
Oct 15 '08 at 14:02
source share
24 answers

Although there are some reasonable reasons to ignore exceptions; however, as a rule, these are only specific exceptions that you can safely ignore. As Conrad Rudolph noted, you may have to catch and internalize the mistake as part of the structure; and, as noted by osp70 , an exception may be thrown by the framework, which, as you know, can be ignored.

In both cases, however, you probably know the type of exception, and if you know the type, then you should have code similar to the following:

 try { // Do something that might generate an exception } catch (System.InvalidCastException ex) { // This exception is safe to ignore due to... } catch (System.Exception ex) { // Exception handling } 

In the case of your application, it sounds like there might be something like this in some cases; but the example that you give the database while keeping OK, even when there is an exception, is not a good sign.

+55
Oct 15 '08 at 14:15
source share

I will not catch exceptions if I am not going to do something with them. Ignoring them does nothing about them.

+16
Oct. 15 '08 at 14:06
source share

I sometimes use WebControl, which is not required to display the page. If this fails, I do not want the page to display. An example of a non-critical WebControl would be one that displays ads.

However, I am logging an error. I just don’t remodel it.

+12
15 Oct. '08 at 14:05
source share

I feel like any empty catch block needs comment.

It may be permissible to ignore certain errors, but you need to document your reasons.

In addition, you will not want to make it general "catch (Exception e) {}".

You should catch only the type of error that was expected there, and is known to be safely ignored.

+11
Oct. 15 '08 at 14:18
source share

Usually not, actually not in 99% of all cases, BUT

There are exceptions. In one project that I was working on, we used a third-party library to process a TWAIN device. This was a mistake, and with some hardware combinations, a null pointer error was selected. However, we never found any circumstances when in fact it was not possible to scan the document before he did it, so the exception was completely rational.

So, I think that if this is your code that throws an exception, then you should always check it, but if you are stuck with third-party code, then in some cases you may be forced to eat the exception and move on.

+8
Oct. 15 '08 at 14:17
source share

In another case, when you can free yourself from catching and ignoring exceptions, this is when you test the device.

 public void testSomething(){ try{ fooThatThrowsAnException(parameterThatCausesTheException); fail("The method didn't throw the exception that we expected it to"); } catch(SomeException e){ // do nothing, as we would expect this to happen, if the code works OK. } } 

Note that although the catch block does nothing, it explains why.

Having said that, the more recent testing framework (Junit4 and TestNG) allow you to specify the expected exception - which leads to something like this ...

 @Test(expected = SomeException.class) public void testSomething(){ fooThatThrowsAnException(parameterThatCausesTheException); fail("The method didn't throw the exception that we expected it to"); } 
+8
Oct. 15 '08 at 14:51
source share

I think from what I find, the best answer is that it may be somewhat acceptable, but should be limited. You should try to use another alternative, and if you cannot find another alternative, you should know enough about how the code works, that you can expect specific types of exceptions, and not just use a blanket for all the “exceptions”. Documentation of the reason for ignoring this exception should be included in an understandable comment form.

+7
Oct 15 '08 at 15:26
source share

in critical code, probably not, because the state of the program must always be precisely determined. as an example of a database call.

in non-critical code, of course, we do this too (we just display the marked exceptions in the message box and continue to work). the plugin or module may not work, but the main program is not affected. lexical_cast may have failed, and a text failure has appeared on the screen. No need to stop the process.

+6
Oct. 15 '08 at 14:07
source share

One example of where I find this acceptable is a non-critical module of a critical application (for example, in the sound feedback module of a spacecraft navigation system), for exceptions that should never occur and cannot be handled more cleanly.

In these cases, you do not want this exception to be distributed and lead to the failure of the entire application (sorry, guys, there’s no longer a navigation system, our sound module did not crash, and there was nothing we could do about it).

Edited to say that in any of these cases, you at least want to register the event in some way.

+5
Oct. 15 '08 at 14:12
source share

I think if you have an empty catch block, you need to document why it is empty so that the next developer will find out. For example, a web exception is sometimes thrown on server.transfer. I will catch this and comment that we can ignore it because of the transfer of the call.

+5
Oct 15 '08 at 14:16
source share

There are, of course, circumstances in which it is normal to catch a specific exception and do nothing. Here's a trivial example:

  public FileStream OpenFile(string path) { FileStream f = null; try { f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); } catch (FileNotFoundException) { } return f; } 

You can also write a method as follows:

  public FileStream OpenFile(string path) { FileStream f = null; FileInfo fi = new FileInfo(path); if (fi.Exists) { f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); } return f; } 

In this case, catching the exception is (very) extremely safe, since the file can be deleted between the time it was checked for its existence and the time it was opened.

There are reasons to not do this, of course. In .NET, exceptions are expensive computational, so you want to avoid everything that throws a lot of them. (In Python, where exceptions are cheap, this is a common idiom for using exceptions to do things like breaking from loops.)

But this ignores the specific exception. This code:

 catch { } 

unforgivable.

There is no good reason not to catch the particular typed exception that the code in the try block is about to throw. The first reason a naive developer gives exceptions for exception, regardless of type: “But I don’t know what type of exception can be thrown,” is a kind of answer to the question.

If you do not know what type of exception can be thrown, you do not know how your code can fail. If you don’t know how your code may fail, you have no reason to believe that it will continue to process normally if this happens.

+5
Oct 15 '08 at 18:37
source share

Yes, its acceptable (inevitable, necessary) under certain circumstances to the post of Maxim. This does not mean that you like it. 2106 is probably too much, and at least they should add a comment in the catch block about why it was okay to swallow this exception.

@Dustin Its bad practice shows any details of an exception for a public user (stack traces, line numbers, etc.). You should probably register an exception and show a common error.

+4
Oct 15 '08 at 14:08
source share

When it comes to Exceptions, there are always exceptions.

+4
Oct. 15 '08 at 14:26
source share

It depends on the structure. Poorly implemented structures may require this. I remember a hack in VB6 where it was not possible to determine if the collection contains an element. The only way is to try to extract the element and learn the error.

+3
Oct. 15 '08 at 14:05
source share

I think a good answer was given to the original question, but I would like to add that if you think that these third-party / contract developers did a poor job, you should make sure that the right people in your company know about them.

It is possible that it may be sent back for revision, that the payment may be partially withheld, or that the same company will no longer be used. If your company uses contractors again, they can find a way to create quality requirements in agreements, assuming they don’t exist there.

If it was an internal work, the consequences for the team / individual that led to poor work will have consequences. Perhaps this would mean that they should work nights and weekends to fix this, but they will somehow be on the hook. The same goes for contractors, perhaps even more so.

Just be careful to explain your position professionally and focus on what is best for the company / product. You do not want it to look like you are just complaining, or that you have some political objection to outsourcing. Do not do this about yourself. Do it about cost, time to market, customer satisfaction, etc. You know, all those things that management types care about.

+2
Oct. 15 '08 at 17:48
source share

I am very interested about this particular one.

 Connection con = DriverManager.getConnection(url, "***", "***"); try { PreparedStatement pStmt = con.prepareStatement("your query here"); ... // query the database and get the results } catch(ClassNotFoundException cnfe) { // real exception handling goes here } catch(SQLException sqle) { // real exception handling goes here } finally { try { con.close(); } catch { // What do you do here? } } 

I never know what to do in this last catch in the finally block. I have never seen to close () throw an exception before, and it is so unlikely that I am not worried about it. I just log the exception and move around.

+2
Oct. 15 '08 at 18:34
source share

If your catch code will not

  • Write exception
  • Reinstall the exception into another exception that matches the same abstraction. and throw it again
  • Handles the exception, as you see suitable

You can ignore the exception, but at least mention the expected exception in the method documents so that the consumer can expect and handle if necessary

+2
Oct. 16 '08 at 5:38
source share

To take an example from the Java world, where it is OK, to ignore the exception:

 String foo="foobar"; byte[] foobytes; try { foobytes=foo.getBytes("UTF-8"); } catch (UnsupportedEncodingException uee) { // This is guaranteed by the Java Language Specification not to occur, // since every Java implementation is required to support UTF-8. } 

However, even in such situations I often use

 ... catch (UnsupportedEncodingException uee) { // This is guaranteed by the Java Language Specification not to occur, // since every Java implementation is required to support UTF-8. uee.printStackTrace(); } 

If the virtual machine is insane / speculative, I can do little with it, but with the stack trace, at least I notice when it began its descent into insanity ...

+2
Oct. 16 '08 at 9:26
source share

This is a very bad thing to do.

Although there are good reasons, you can ignore exceptions - if they are expected in some way and there is no need to do anything about it, but in 2000 it seems like they just want to sweep their exceptions under the rug.

Examples of where it is normal to catch exceptions may be trial for things ... you send a message to some device or module, but you don't care if it really got there.

+1
Oct 15 '08 at 14:13
source share

The following words apply only to languages ​​that check for exceptions, for example. Java:

Sometimes a method throws a checked exception, which, as you know, will not happen, for example. some Java APIs expect a string encoding name and throw an UnsupportedEncodingException if this encoding is not supported. But usually I pass the literal "UTF-8", which, as I know, is supported, so I could theoretically write an empty entry.

Instead of doing this (an empty catch), I usually throw a generic unchecked exception, wrapping an "impossible" exception, or even declare the ImpossibleException class that I throw. Because my theory that this error condition is impossible may be wrong, and in this case I would not want the exception to be swallowed.

+1
Oct 15 '08 at 15:09
source share

I like to let almost all of my exceptions bubble up to the application handler, where they are logged, and the general error message is displayed to the end user. But the caveat here is that there really shouldn't be so many exceptions. If your application throws many exceptions, then something is probably wrong or something that could be better encoded. For the most part, I try to have my code check for exceptional cases in advanced mode, because throwing exceptions is expensive.

Aside, outsourcing coding is usually a bad idea. In my experience, as a rule, they are consultants who are only in this for a salary and have no share in the success of the project. In addition, you abandon your coding standards (if you have not included this in the contract).

+1
Oct. 15 '08 at 16:22
source share

Think of it this way: if you spend CPU cycles to catch an exception but then swallow, you ignore the potential problem and waste the processor. As many have said, an application should not throw many exceptions unless you have a poorly built one.

+1
Oct. 15 '08 at 18:46
source share

We have an application that processes a lot on behalf of other applications, where you insert some kind of task (configuration collection) into the database, and the application will accept it and run it at the appropriate time. We tend to catch a lot of exceptions in this application, because even if Job1 dies horribly, with a catastrophic error, we want the application to stay alive in order to get hit when processing Job2.

+1
Dec 10 '08 at 21:15
source share

I think the best rule of thumb is to ignore only exception if you are fully aware of what exception is and the possible consequences of this. In the case of some kind of isolated module that does not affect the rest of your system, I think it would be normal to just catch the general exception if you know that nothing bad happens to anything else.

IMO is easier to know forks in Java, since each method must declare all exceptions that it can throw so that you know what to expect, but in C # an exception can be thrown even if it is not documented, so it's hard to know all the possible exceptions that can be selected by the method, and without this knowledge, it is usually difficult to catch everything.

0
Oct 15 '08 at 14:40
source share



All Articles