Why do Java people often consume exceptions silently?

I had never done serious Java encodings before, but I learned the syntax, libraries, and concepts based on my existing skills (Delphi and C #). One thing that I almost don't understand is that I saw so much code that silently consumes exceptions after printStackTrace as follows:

  public void process() { try { System.out.println("test"); } catch(Exception e) { e.printStackTrace(); } } 

Similar code is similar to this in almost every article and Java project I came across. Based on my knowledge, this is very bad. An exception should almost always be sent to an external context as follows:

  public void process() { try { System.out.println("test"); } catch(Exception e) { e.printStackTrace(); throw new AssertionError(e); } } 

In most cases, the exception should be handled in the outermost loop, which refers to the underlying structure (e.g. Java Swing). Why does it look like the norm for code like this in the Java world? I am puzzled.

Based on my assumption, I would prefer to completely remove printStackTrace. I would simply refuse as an unhandled aka RuntimeException (or, even better, an AssertionError ), and then catch and fire it in the most appropriate place: the outermost loop.

  public void process() { try { System.out.println("test"); } catch(Exception e) { throw new AssertionError(e); } } 
+70
java exception exception-handling
May 28 '09 at 15:26
source share
28 answers

I always thought it looked like the following scenario:

"The man gets a shot.

He holds his breath and is strong enough to catch the bus.

After 10 miles, a person gets off the bus, walks in pairs of blocks and dies. "

When the police get to the body, they don’t have a clue about what just happened. In the end, perhaps this is a lot more complicated.

Better:

"A man gets shot, and he dies instantly, and the body lies exactly where the killing just happened."

When the police arrive, all evidence is available.

If the system fails, it’s better to complete a quick run.

Solution of the problem:

  • Ignorance.
    • +
  • Laziness

EDIT:

Of course, the catch section is useful.

If something can be done with an exception, then where should it be done.

This is probably NOT an exception for this code, perhaps this is what is expected (and by my analogy it looks like a bulletproof jacket, and the man was waiting for the shot in the first place).

And yes, the catch can be used to Throw exceptions corresponding to abstractions

+183
May 28, '09 at 15:44
source share

This is usually because the IDE offers a useful “quick fix” that wraps the violation code in a try-catch block with this exception handling. The idea is that you are actually doing something, but lazy developers do not.

This is a bad form, no doubt.

+32
May 28 '09 at 15:30
source share
  • Java makes you handle all Exceptions explicitly. If the method called by your codes declares a FooException and a BarException, your code MUST handle (or remove) these exceptions. The only exception to this is a RuntimeException, which ticks like a ninja.
  • Many programmers are lazy (including me), and it is very simple to print a stack trace.
+19
May 28 '09 at 3:28
source share

This is a classic straw argument . printStackTrace() is a debugging aid. If you saw him on a blog or in a magazine, this was because the writer was more interested in illustrating a point other than exception handling. If you saw this in production code, the developer of this code was clueless or lazy, nothing more. This should not be taken as an example of common practice in the "Java world."

+18
May 28 '09 at 15:56
source share

I find that this is often 2 reasons.

  • The programmer was lazy
  • The programmer wanted to guard the entry point to the component (right or wrong)

I do not think this phenomenon is limited to Java. I often saw such coding in C # and VB.Net.

At first glance, this is quite shocking and looks awful. But this is actually nothing new. This happens all the time in C ++ applications that use error code return values ​​compared to exceptions. The difference is that ignoring a potentially fatal return value does not really look different than calling a function that returns void.

 Foo* pFoo = ...; pFoo->SomeMethod(); // Void or swallowing errors, who knows? 

This code looks better, but if SomeMethod () should have returned HResult, it would be semantically no different from swallowing an exception.

+12
May 28 '09 at 15:31
source share

because Checked Exceptions are a failed experiment

(maybe printStackTrace () is the real problem ? :)

+11
May 28, '09 at 15:28
source share

I have to say that I am slightly outraged by the tone, which implies that such behavior in error handling is something fundamental for Java programmers. Of course, Java programmers can be lazy like any other programmer, and Java is a popular language, so you are likely to see a lot of mistakes when swallowing code.

In addition, as indicated elsewhere, there are understandable frustrations with forcing Java to declare checked exceptions, although personally I have no problem with this.

I have a problem with, I think, that you are a breeze through a bunch of articles and code snippets on the Internet, without bothering to consider the context. In truth, when you write a technical article trying to explain how a particular API works, or how to start with something, then you are likely to miss some aspects of the code - error handling, which is not directly related to what you demonstrate is a likely candidate for deletion, especially if an exception is unlikely to happen in the sample script.

People who write articles of this nature should maintain a reasonable signal-to-noise ratio, and fairly, I think, this means that they should assume that you know some of the basics of the language in which you are developing; how to deal with errors and a bunch of other things. If you come across any article and notice the lack of proper error checking, then this is fine; just make sure that when you incorporate these ideas (but, of course, you are never the exact code, are you?) in your production code, you will be dealing with all these bits and beans that the author reasonably missed, thus that most are suitable for what you design.

I have a problem with very high-level introductory articles that do such problems without even returning to them, but please keep in mind that there is no specific “thinking” for Java programmers regarding error handling; I know a lot of your favorite C # programmers who are also not worried about all their problems.

+6
May 28 '09 at 23:59
source share

Fingerprint of System.out or e.printStackTrace () - which implies the use of System.out, usually a red flag, meaning that someone did not bother to do the hard work. With the exception of Java desktop applications, most Java applications make better use of logging.

If the failure mode for the method is inoperative, it is great to have an exception, whether you write down the reason (and existence) or not. More typically, however, a catch clause must take some kind of exceptional action.

Re-creating an exception is what is best done when you either use catch to clear some of the work at a level where the necessary information is still available, or when you need to convert the exception to an exception type more suitable for the caller.

+5
May 28 '09 at 16:00
source share

It is consumed only quietly if the catch block is really empty.

As for the articles, they are probably more interesting in proving some other points, in addition to how to deal with exceptions. They just want to get straight to the point and have the shortest code.

Obviously, you are right, but exceptions should be registered if they are “ignored”.

+3
May 28 '09 at 15:30
source share

As others have pointed out, the reason you see this is due to one of three reasons:

  • Try-catch block created in IDE
    • The code has been copied and pasted.
    • The developer set stacktrace for debugging, but never returned to handle the exception normally.

The last point is the least likely. I say this because I do not think that anyone is really debugging this way. Running code with a debugger is a much easier way to debug.

A better description of what needs to be done in the catch block can be found in Chapter 9, Effective Java by Joshua Bloch .

+3
May 28 '09 at 10:04
source share

In C #, all exceptions are runtime exceptions, but in Java you have runtime exceptions and checked exceptions that you must either catch or declare in your methods. If you call any method that has “throws” at the end, you must either catch the exceptions mentioned there, or your method should also declare these exceptions.

Java articles usually just print a stack trace or have a comment, since exception handling is not relevant to the subject of the article. In projects, however, something needs to be done about this, depending on the type of exception.

+2
May 28, '09 at 15:32
source share

You should see this very often if the programmer does his job correctly. Ignoring Exceptions is bad, bad practice! But there are some reasons why some can do this and more convenient solutions:

  • "It will not happen!" Undoubtedly, someday you “know” that this exception will not happen, but it is even more advisable to reconstruct the exception at run time, while the Exception is the “reason” instead of just ignoring it. I bet it will happen in the future .; -)

  • Prototyping Code If you just print your materials to see if this works, you can ignore all the Exceptions that may arise. This is the only time I am doing a lazy catch (Throwable). But if the code turns into something useful, I will include the correct exception handling.

  • "I do not know what to do!" I saw a lot of code, especially library code, which swallows exceptions, because proper processing cannot be performed at this application level. Do not do this! Just flip the exception (either by adding a throws clause to the method signature, or by wrapping the exception in a specific library).

+2
May 28, '09 at 15:39
source share

You should always forward it or treat it appropriately in the real world. Many articles and tutorials will simplify their code to get more important points, although one of the simplest things to simplify is error handling (unless you are writing an article about error handling: :)). Since java code will check for exception handling, a simple proxy file (or log file) is the easiest way to provide a working example.

If you find this in anything other than example code, feel free to forward the code to TDWTF, although they may have too many examples of it :)

+2
May 28, '09 at 15:44
source share

The combination of checked exceptions and interfaces causes the code to process outputs that will never be thrown. (The same goes for normal inheritance, but this is more common and easier to explain using interfaces)

Reason: an interface implementation cannot exclude (check) exceptions other than those defined in the interface specification. For this reason, the creators of the interface, not knowing which methods of the class that implements the interface, should indeed throw an exception, can indicate that all methods can raise at least one type of exception. Example: JDBC, where it is announced that everyone and his grandmother throw a SQLException.

But in fact, many methods of real implementations simply cannot fail, therefore, under no circumstances will they ever throw an exception. The code that calls these methods must still handle the exception, and the easiest way is to catch the exception. No one wants to clutter up their code with seemingly useless error handling that will never be executed.

+2
May 29 '09 at 11:47
source share

As indicated, calling printStackTrace () is not really silent processing.

The reason for this kind of “swallowing” an exception is that if you continue to pass the exception in the chain, you still have to handle the exception somewhere or allow the application to crash. Thus, handling it at a level that occurs with the help of an information dump is no worse than processing it at the upper level with the help of an information dump.

+1
May 28 '09 at 15:33
source share

His lazy practice - there's nothing to be done.

This is usually done when you really don't care about the exception - instead of enlarging your fingers.

+1
May 28 '09 at 16:17
source share

I disagree that rethinking the checked exception is the best idea. Trick means processing; if you need to remodel, you should not catch. In this case, I will add a throw clause to the method signature.

I would say that moving a checked exception to an unchecked one (for example, Spring's method wraps a checked SQLException in an instance of its unchecked hierarchy) is acceptable.

Logging can be seen as processing. If this example was modified to write a stack trace using log4j instead of writing to the console, would that make it acceptable? Not much change, IMO.

The real problem is what is considered an exceptional and acceptable recovery procedure. If you cannot recover from an exception, it is best to report an error.

+1
May 28 '09 at 21:51
source share

The real point of exceptions is to simplify error handling and separate it from error detection. This contradicts the presentation of errors by error codes, where error processing codes are scattered throughout, and every call that may fail should be checked for a return code.

If the exception is an error (in most cases), then the most reasonable way to eliminate it is to save and leave the processing to some upper level. Repeating a different exception, it should be taken into account if significant semantics are added to it, that is, this error is an unusual system error / temporary (network) problem / this is an error on the client or server side, etc.

Of all the error handling strategies, the most ignorant are hiding or simply printing an error message and moving forward because nothing happened.




Sun people wanted the code to be a more explicit and coercive programmer to write which exceptions could be thrown using which method. This seemed to be the right move - anyone knows what to expect in return from any method call with its prototype (it can return a value of this type or throw an instance of one of the specified classes (or its subclass)).

But, as it turned out, with a lot of uninformed Java programmers, they now consider exception handling as if it were a language error / “function” that needed a workaround and code writing in the worst or almost least possible way:

  • The error is processed immediately in a context that is not suitable for deciding what to do with it.
  • It is displayed or ignored silently, and calculations continue, even if the additional code does not work properly.
  • The calling method cannot tell if it completed successfully or not.



How to write the "right way" than?

  • Indicate each base exception class that can be selected in the method header. AFAICR Eclipse can do this automatically.
  • Make the cast list in the prototype method significant. Long lists are pointless, and a “throw Exception” is lazy (but useful when you don’t worry much about exceptions).
  • When writing the “wrong way”, the simple “throwing an exception” is much better and takes less bytes than “try {...} catch (Exception e) {e.printStackTrace ();}”.
  • Retrow chained exception if necessary.
+1
May 28 '09 at
source share

I’m afraid that most Java programmers don’t know what to do with Exceptions, and quite often consider it an annoyance that slows down their coding of the “nominal” case. Of course, they are completely wrong, but it is difficult to convince them that it is important to deal with exceptions correctly. Every time I meet such a programmer (this happens often), I give him two entries:

  • famous Thinking In java
  • A short and interesting article by Barry Ruzek is available here: www.oracle.com/technology/pub/articles/dev2arch/2006/11/effective-exceptions.html

By the way, I strongly agree that it is foolish to catch a typed exception to reset it to a RuntimeException:

  • , HANDLE.
  • , , / , .
+1
29 '09 6:53
source share

, .

, , , , , , , .

: - . ... , , , . - ... , . , , , , .

+1
09 . '09 12:15
source share

:

 class ExceptionUtils { public static RuntimeException cloak(Throwable t) { return ExceptionUtils.<RuntimeException>castAndRethrow(t); } @SuppressWarnings("unchecked") private static <X extends Throwable> X castAndRethrow(Throwable t) throws X { throw (X) t; } } class Main { public static void main(String[] args) { // Note no "throws" declaration try { // Do stuff that can throw IOException } catch (IOException ex) { // Pretend to throw RuntimeException, but really rethrowing the IOException throw ExceptionUtils.cloak(ex); } } } 
+1
31 . '10 20:12
source share

, , , "throws" .

try/catch, , , , , .

0
28 '09 15:34
source share

, " " . , , , " ".

0
28 '09 15:35
source share

, , . IOExcetion, . , ? Jakarta DBUtils .

, , ( - ), . , , printStackTrace(). RuntimeException -. - , createClientAccount() throws ProgrammingErrorException ( SQLException), , sql .

0
28 '09 16:19
source share

, , , . , , , , , , , , .

Fail-Fast/Fail-HARD, , , . "" ( : {}) - DAYS, .

, Java , , , . Thread.sleep(). , , , , , , . .

0
29 '09 0:11
source share

, catch. , RuntimeExceptions - , , ? : , .

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

0
29 '09 11:32
source share

, , . , - . , , , , , .

, , ; , , , .

BTW: ,

 try { // do something } catch (Throwable e) { // do something with the exception Thread.currentThread().stop(e); // doesn't actually stop the current thread, but throws the exception/error/throwable } 

Note. , , throws , .

0
11 . '09 14:59
source share

. , .
, , . C .

-2
28 '09 15:58
source share



All Articles