Skip to content Skip to sidebar Skip to footer

Ask User if They Would Like to Play Again Java

This post is another add-on in all-time practices series available in this blog. In this post, I am covering some well-known and some little known practices which you must consider while handling exceptions in your adjacent java programming assignment. Follow this link to read more nearly exception handling in java.

          Table of Contents          Type of exceptions User defined custom exceptions          Best practices you must consider and follow          Never eat the exception in catch cake Declare the specific checked exceptions that your method can throw Do not catch the Exception class rather catch specific sub classes Never take hold of Throwable class Always correctly wrap the exceptions in custom exceptions then that stack trace is not lost Either log the exception or throw it but never do the both Never throw whatsoever exception from finally cake Ever catch only those exceptions that y'all can actually handle Don't use printStackTrace() argument or similar methods Apply finally blocks instead of catch blocks if you are non going to handle exception Remember "Throw early catch tardily" principle E'er make clean upward later handling the exception Throw only relevant exception from a method Never apply exceptions for menstruum control in your program Validate user input to grab adverse atmospheric condition very early on in request processing Always include all data nigh an exception in unmarried log message Pass all relevant information to exceptions to brand them informative equally much as possible Ever stop the thread which it is interrupted Employ template methods for repeated try-catch Document all exceptions in your application in javadoc

Earlier nosotros dive into deep concepts of exception handling all-time practices, lets beginning with one of the well-nigh important concepts which is to understand that there are three full general types of throwable classes in Java: checked exceptions, unchecked exceptions, and errors.

i. Blazon of exceptions in Java

exceptionhierarchy3-8391226
Exception Hierarchy in java

Checked exceptions

These are exceptions that must exist declared in the throws clause of a method. They extend Exception and are intended to exist an "in your face" type of exceptions. Java wants you to handle them because they somehow are dependent on external factors outside your program. A checked exception indicates an expected trouble that tin can occur during normal system performance. Mostly these exception happen when you try to utilise external systems over network or in file organisation. Mostly, the correct response to a checked exception should be to attempt once again later, or to prompt the user to change his input.

Unchecked exceptions

These are exceptions that do not need to be declared in a throws clause. JVM only doesn't force you to handle them as they are more often than not generated at runtime due to programmatic errors. They extend RuntimeException. The most common instance is a NullPointerException [Quite scary.. Isn't it?]. An unchecked exception probably shouldn't be retried, and the correct action should exist usually to do nothing, and let it come out of your method and through the execution stack. At a high level of execution, this type of exceptions should be logged.

Errors

are serious runtime environment issues that are most certainly not recoverable. Some examples are OutOfMemoryError, LinkageError, and StackOverflowError. They by and large crash you plan or part of programme. Simply a good logging practice will help you in determining the exact causes of errors.

2. User defined custom exceptions

Someday when user feels that he wants to utilise its own application specific exception for some reasons, he can create a new class extending appropriate super class (mostly its Exception) and start using it in appropriate places. These user defined exceptions can be used in 2 ways:

  1. Either directly throw the custom exception when something goes wrong in application
    throw new DaoObjectNotFoundException("Couldn't detect dao with id " + id);
  2. Or wrap the original exception inside custom exception and throw it
    catch (NoSuchMethodException e) {   throw new DaoObjectNotFoundException("Couldn't find dao with id " + id, east); }

Wrapping an exception tin can provide extra data to the user by calculation your ain message/ context information, while notwithstanding preserving the stack trace and bulletin of the original exception. Information technology also allows you to hibernate the implementation details of your lawmaking, which is the most important reason to wrap exceptions.

Now lets beginning exploring the best practices followed for exception handling manufacture wise.

3. Java exception treatment all-time practices you must consider and follow

3.ane. Never consume the exception in catch block

take hold of (NoSuchMethodException due east) {    return null; }        

Doing this not only return "null" instead of handling or re-throwing the exception, information technology totally swallows the exception, losing the cause of error forever. And when yous don't know the reason of failure, how you would prevent information technology in futurity? Never do this !!

iii.two. Declare the specific checked exceptions that your method can throw

public void foo() throws Exception { //Incorrect way }        

Always avert doing this as in above code sample. It simply defeats the whole purpose of having checked exception. Declare the specific checked exceptions that your method can throw. If in that location are but too many such checked exceptions, yous should probably wrap them in your own exception and add information to in exception message. You tin can too consider code refactoring as well if possible.

public void foo() throws SpecificException1, SpecificException2 { //Correct way }        

3.3. Do not catch the Exception class rather take hold of specific sub classes

endeavour {    someMethod(); } catch (Exception e) {    LOGGER.error("method has failed", east); }        

The problem with catching Exception is that if the method you are calling later adds a new checked exception to its method signature, the programmer's intent is that yous should handle the specific new exception. If your code just catches Exception (or Throwable), you lot'll never know about the change and the fact that your lawmaking is now wrong and might break at any point of time in runtime.

three.4. Never catch Throwable class

Well, its one step more than serious trouble. Because java errors are also subclasses of the Throwable. Errors are irreversible weather that tin can non be handled by JVM itself. And for some JVM implementations, JVM might non actually even invoke your take hold of clause on an Error.

3.5. Ever correctly wrap the exceptions in custom exceptions and so that stack trace is not lost

catch (NoSuchMethodException due east) {    throw new MyServiceException("Some information: " + e.getMessage());  //Incorrect way }        

This destroys the stack trace of the original exception, and is always wrong. The right manner of doing this is:

catch (NoSuchMethodException e) {    throw new MyServiceException("Some information: " , e);  //Correct way }        

3.six. Either log the exception or throw it only never exercise the both

catch (NoSuchMethodException east) {    LOGGER.error("Some information", e);    throw due east; }        

As in above example code, logging and throwing will result in multiple log messages in log files, for a single trouble in the code, and makes life hell for the engineer who is trying to dig through the logs.

3.7. Never throw any exception from finally block

try {   someMethod();  //Throws exceptionOne } finally {   cleanUp();    //If finally also threw whatever exception the exceptionOne will be lost forever }        

This is fine, every bit long as cleanUp() can never throw any exception. In the above example, if someMethod() throws an exception, and in the finally block also, cleanUp() throws an exception, that second exception will come out of method and the original first exception (correct reason) volition be lost forever. If the lawmaking that you call in a finally cake can possibly throw an exception, make sure that you either handle it, or log it. Never let it come out of the finally cake.

3.eight. Ever catch only those exceptions that y'all can actually handle

catch (NoSuchMethodException due east) {    throw e; //Avoid this every bit information technology doesn't help anything }        

Well this is most important concept. Don't take hold of any exception but for the sake of catching it. Catch any exception simply if yous desire to handle information technology or, you want to provide additional contextual information in that exception. If you can't handle it in take hold of block, then best advice is just don't catch information technology only to re-throw it.

iii.9. Don't use printStackTrace() argument or similar methods

Never leave printStackTrace() after finishing your code. Chances are i of your fellow colleague will get i of those stack traces somewhen, and take exactly zero knowledge as to what to do with information technology because it will not have whatsoever contextual information appended to it.

three.x. Use finally blocks instead of take hold of blocks if you are non going to handle exception

endeavor {   someMethod();  //Method 2 } finally {   cleanUp();    //practise cleanup here }        

This is also a skillful practice. If inside your method you lot are accessing some method ii, and method ii throw some exception which you do not want to handle in method 1, but still desire some cleanup in case exception occur, then do this cleanup in finally block. Do not use catch cake.

three.11. Recall "Throw early take hold of belatedly" principle

This is probably the nearly famous principle near Exception handling. Information technology basically says that you should throw an exception equally presently as you tin, and catch it tardily as much every bit possible. You should await until yous have all the information to handle it properly.

This principle implicitly says that you will exist more likely to throw information technology in the depression-level methods, where you will be checking if single values are zero or not appropriate. And yous will be making the exception climb the stack trace for quite several levels until you reach a sufficient level of abstraction to exist able to handle the trouble.

3.12. Always make clean up after treatment the exception

If you are using resources like database connections or network connections, make sure you clean them up. If the API you are invoking uses but unchecked exceptions, you should nevertheless clean up resources afterward use, with try – finally blocks. Inside attempt block access the resources and inside finally close the resource. Fifty-fifty if any exception occur in accessing the resources, then likewise resource will be closed gracefully.

3.13. Throw just relevant exception from a method

Relevancy is important to keep application clean. A method which tries to read a file; if throws NullPointerException then it will not give any relevant information to user. Instead it volition be better if such exception is wrapped inside custom exception e.g. NoSuchFileFoundException then information technology will be more useful for users of that method.

3.14. Never use exceptions for flow control in your program

We have read information technology many times but sometimes nosotros continue seeing lawmaking in our project where developer tries to use exceptions for application logic. Never do that. It makes code hard to read, sympathise and ugly.

3.fifteen. Validate user input to catch adverse conditions very early in request processing

Always validate user input in very early phase, even before it reached to actual controller. It volition help you to minimize the exception handling code in your cadre application logic. Information technology too helps you lot in making application consistent if there is some mistake in user input.

For example: If in user registration application, you are following beneath logic:

1) Validate User
2) Insert User
3) Validate address
iv) Insert address
5) If trouble the Rollback everything

This is very incorrect approach. It tin leave you lot database in inconsistent land in various scenarios. Rather validate everything in first identify and then have the user data in dao layer and make DB updates. Right approach is:

1) Validate User
two) Validate accost
3) Insert User
four) Insert address
5) If problem the Rollback everything

3.16. Ever include all data most an exception in single log message

LOGGER.debug("Using cache sector A"); LOGGER.debug("Using retry sector B");

Don't do this.

Using a multi-line log bulletin with multiple calls to LOGGER.debug() may look fine in your test case, but when it shows up in the log file of an app server with 400 threads running in parallel, all dumping information to the aforementioned log file, your two log messages may end up spaced out 1000 lines apart in the log file, even though they occur on subsequent lines in your code.

Do it like this:

LOGGER.debug("Using enshroud sector A, using retry sector B");

three.17. Pass all relevant information to exceptions to make them informative as much as possible

This is also very important to make exception letters and stack traces useful and informative. What is the use of a log, if you are not able to determine anything out of it. These type of logs but exist in your code for ornament purpose.

iii.18. Always end the thread which it is interrupted

while (true) {   try {     Thread.sleep(100000);   } catch (InterruptedException e) {} //Don't practise this   doSomethingCool(); }        

InterruptedException is a clue to your code that information technology should terminate whatever it's doing. Some common use cases for a thread getting interrupted are the active transaction timing out, or a thread pool getting shut down. Instead of ignoring the InterruptedException, your lawmaking should do its best to finish up what it's doing, and end the electric current thread of execution. So to correct the example to a higher place:

while (true) {   endeavour {     Thread.sleep(100000);   } catch (InterruptedException e) {     break;   } } doSomethingCool();        

3.xix. Use template methods for repeated try-catch

There is no use of having a similar catch cake in 100 places in your lawmaking. It increases lawmaking duplicity which does not assistance anything. Use template methods for such cases.

For case below lawmaking tries to close a database connection.

class DBUtil{     public static void closeConnection(Connection conn){         try{             conn.close();         } catch(Exception ex){             //Log Exception - Cannot close connectedness         }     } }        

This type of method volition be used in thousands of places in your awarding. Don't put whole code in every place rather define higher up method and use it everywhere similar beneath:

public void dataAccessCode() {     Connection conn = aught;     try{         conn = getConnection(); 		....     } finally{         DBUtil.closeConnection(conn);     } }        

iii.20. Document all exceptions in the application with javadoc

Make information technology a practice to javadoc all exceptions which a piece of lawmaking may throw at runtime. As well try to include possible grade of action, user should follow in case these exception occur.

That's all i have in my mind for now related to Java exception handling best practices. If you found anything missing or you does not relate to my view on any bespeak, driblet me a comment. I volition be happy to discuss.

Happy Learning !!

schulertrook1972.blogspot.com

Source: https://howtodoinjava.com/best-practices/java-exception-handling-best-practices/

Postar um comentário for "Ask User if They Would Like to Play Again Java"