![]() ![]() An unchecked exception probably shouldn’t be retried, and the correct action should be usually to do nothing, and let it come out of your method and through the execution stack. The most common example is a NullPointerException. JVM simply doesn’t force you to handle them as they are mostly generated at runtime due to programmatic errors. Unchecked exceptions are exceptions that do not need to be declared in a throws clause. Mostly, the correct response to a checked exception should be to try again later, or to prompt the user to modify his input. Mostly these exception happen when you try to use external systems over network or in file system. A checked exception indicates an expected problem that can occur during normal system operation. Java wants you to handle them because they somehow are dependent on external factors outside your program. They extend Exception and are intended to be an “in your face” type of exceptions. Type of exceptionsĬhecked exceptions are exceptions that must be declared in the throws clause of a method. Document all exceptions in your application in javadocīefore we dive into deep concepts of exception handling best practices, lets start with one of the most important concepts which is to understand that there are three general types of throwable classes in Java: checked exceptions, unchecked exceptions, and errors.Use template methods for repeated try-catch.Always terminate the thread which it is interrupted.Pass all relevant information to exceptions to make them informative as much as possible.Always include all information about an exception in single log message.Validate user input to catch adverse conditions very early in request processing.Never use exceptions for flow control in your program.Throw only relevant exception from a method.Always clean up after handling the exception. ![]() Remember "Throw early catch late" principle.Use finally blocks instead of catch blocks if you are not going to handle exception.Don't use printStackTrace() statement or similar methods.Always catch only those exceptions that you can actually handle.Never throw any exception from finally block.Either log the exception or throw it but never do the both.Always correctly wrap the exceptions in custom exceptions so that stack trace is not lost.Do not catch the Exception class rather catch specific sub classes.Declare the specific checked exceptions that your method can throw.Never swallow the exception in catch block.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |