Java Exceptions, What to Catch and What Not?

I keep getting terrible java.something.someException errors when starting a java application. and I don’t seem to understand what exceptions to handle and what not?
When I read api docs, most functions throw exceptions, for example if I use I / O or use Array ... etc.

How to decide which exceptions to catch and what not, and based on what parameters?

I am talking about the exceptions noted.

+7
java exception
source share
8 answers

Short answer

Catch the exceptions that you can deal with then and there, rethrow what you cannot.

Long answer

He called the exception handling code for some reason: whenever it is tempting to write a catch , you must have a good reason to catch the exception in the first place. The catch indicates your intention to catch the exception and then do something. Examples of something with this include, but are not limited to:

  • Retrying the operation that caused the exception. This may make sense in the case of an IOException and other problems that may be temporary (for example, a network error in the middle of trying to upload a file to the server. Perhaps your code should retry downloading several times).

  • Exception record. Yes, journaling is considered something. You may also want to throw the original exception again after it is registered so that another code can still handle this exception, but it depends on the situation.

  • An exception wrapper in another exception, more suitable for your class interface. For example, if you have a FileUploader class, you can wrap an IOException in a more general UploadFailedException so that classes using your class do not need to know in detail how your loading code works (the fact that it throws a IOException is technically an implementation detail) .

If the code cannot intelligently do anything about the problem at the point where it occurs, then you should not catch it at all.

Unfortunately, such strict rules never work in 100% of cases. Sometimes, the third-party library that you use throws checked exceptions that you really don't like or that will never happen. In these cases, you can get rid of using an empty catch that does not run any code, but this is not recommended for eliminating exceptions. At the very least, you should add a comment explaining why you ignore the exception (but like CPerkins in the comments, “never say never.” You want to actually register these types of exceptions “never happen”, so just in case such an exception occurs, you know about it and you can continue the study).

However, the general rule is that if the method you are in cannot do something reasonable with the exception (write it down, restart, repeat the operation, etc.), then you should not write a catch generally. Let the invocation method deal with the exception. If you are dealing with checked exceptions, add an excluded exception to the throws your method, which tells the compiler to throw the exception up to the calling method, which may be better suited to handling the error (the calling method may have more context, so it can better understand how to handle an exception).

It is usually useful to add try...catch to your main method, which will catch all exceptions that your code cannot handle, and report this information to the user and gracefully exit the application.

And finally, don't forget about finally

Also keep in mind that even if you are not writing a catch , you still have to write a finally block if you need cleansing code to run regardless of whether the operation you are trying to execute exceptions or exceptions is performed. A common example is opening a file in a try block: you still want to close the file, even if an exception occurs, and even if your method does not catch the exception. In fact, another general rule that you can see in textbooks and books is that try...finally blocks should be more common in try...catch blocks in your code, precisely because catch blocks should only be written when you really can handle the exception, but finally blocks are needed when your code needs to be cleaned after itself.

+15
source share

I highly recommend Chapter 9 (Exceptions) in Joshua Bloch Effective Java, 2nd Edition on this issue.

+5
source share

The general rule is to handle those exceptions that you can do something, and not to handle those that you cannot. In cases where you are not handling the exception, the caller must handle them. If you are writing a framework or library, you end up wrapping exceptions at the lower level, such as a SQLException in the library or a specific exception for a particular structure, to abstract from the details of the lower level.

For example, if you are writing a method that writes to a file on disk, you should probably handle FileNotFoundException , since you can create a missing file, but if you have problems creating or writing to the file, you should probably allow the handler can handle this (after any cleaning work has to be completed).

+4
source share

These are my personal findings:

  • You need to try {} catch (Throwable o) {...} in your main routine so that any unexpected exception can be caught, registered and reported to the user.
  • Checked exceptions are checked because you need to decide as a programmer what to do when they happen. Remember that one solution may be to simply say “okay, time to crash”.
  • If you end up with a fatal situation with a checked exception, where all you can do is fail, then throw new RuntimeException ("reason", checkedException); therefore, the handler above must write something. Include the value of important local variables. Remember that one day you will have to debug a situation where the only thing you have is a stack trace.
  • Never, never catch an exception and just ignore it. If you need to, then you must document why you are allowed to break the rule, and do it right there, in the catch block.

And a hint that will help you someday: when you fail, provide a simple tool that allows the user to see the message sending you a stack trace.


EDIT: Don't be afraid to create new exceptions if those that are available do not fully cover what you need. This allows you to better name the stack trace, and your error handling code can easily distinguish between different cases. You can use all of your own exceptions in the common base class ("OurDomainException") so you can use the base class in catch clauses to find out if it has a type.

+3
source share

Having encoded Java for several years, I agree that it's easy to get angry by writing endless try-catch blocks.

A good way to code is that you catch certain exceptions as low as you can and catch the Exception base at the most remote level (in main() ) so that you can write a general error message to resolve the program crash instead.

This allows you to quickly run the code, and then you can spend your time to add certain exceptions to different levels using processing logic.

+2
source share

Catch checked Exception , do not catch RuntimeException . Try to catch a specific exception, try not to catch the general java.lang.Exception .

+2
source share

Module Boundaries

I also rule out exceptions for cleaner module boundaries. For example, if there is a called SQLException that I cannot handle, I will catch it anyway and instead make my own descriptive exception instead (including SQLException as the reason). Thus, the caller does not need to know that I am using the database to fulfill his request. It just gets the error "Unable to process this specific use case." If I decide to execute his query without access to the database, I do not need to change my API.

+1
source share

Typically, I break exceptions when I can do something about it or where I want the exception to stop moving up. For example, if I process a list of elements and I want the next element to be processed, even if others fail, then I will put a try ... catch block around this element processing and only there. Usually I try ... to catch (Throwable) in the main method of my program so that I can register errors as a class, not found or similar material.

I do not put try ... catch block in the method unless I know what to do with this exception. If you do this, you simply inflate your code with lots of exception handling code.

0
source share

All Articles