MyPage is a personalized page based on your interests.The page is customized to help you to find content that matters you the most.


I'm not curious

Tutorial on Best Practices for Java Exception Handling

Published on 02 June 16
1604
0
1

Exception can be defined as an error event that could occur during the execution of a program and it thus causes the normal flow to be disrupted. Java Exception Handling is offered by Java to handle such scenarios in an object-oriented and robust way. We will look in detail the various best practices on offer by Java Exception Handling.

Overview of Java Exception Handling

Even though no one would like to see exceptions occurring, users will have to deal with it in some or other manner. Java Exception Handling framework has been designed as robust and easy to use framework. There are several factors that might have contributed for the exceptions. The reasons could be failure of hardware, failure of the network connection, database server down or it can be because of wrong data being entered by the user.

Java creates an exception object whenever an error happens while executing a statement and thus leading to the stoppage of normal flow of program. JRE would then look in to someone who would be capable of handling the exception being raised. The exception object is comprised of a lot of debugging information ranging from method hierarchy, type of exception and the line number on which the exception actually occurred. If an exception object is created and is handed over to a Run-time Environment whenever an exception occurs in a method, then it is known as ‘throwing the exception’. The handler would be then identified for the exception and once identified the exception object would be then passed on to the handler for processing it. The handler is supposed to be performing process known as ‘Catching the Exception’.

Exception Handling Keywords

Specific keywords are offered by Java for exception handling purposes.

Throw - This keyword is used to throw exception to the run-time for handling it.

Throws – This keyword is used in method signature so as to allow the program to know the possibility of exceptions that might be likely thrown by the method. The exceptions would be handled by the caller method or it could be propagated to the caller method by making use of the throws keyword.

Try-catch – For exception handling in code, the try-catch block is usually used. Try signifies the start of the block where as Catch signifies the end of the try block when it comes to handling the exceptions. However it is necessary for a catch block to have a parameter that is of type Exception.

Finally – This keyword is optional and could be used only with try-catch block. Finally block could be used during instances wherein some resources would be open and does not get closed when exception halts the process of execution.

Exception Hierarchy

As we all know that exception object is created whenever any exception is being raised. Java exceptions are represented as hierarchical and different types of exceptions are categorized by making use of inheritance. The parent class of Java Exceptions Hierarchy is Throwable and it is usually comprised of two child objects namely Error and Exception. The exceptions however are further classified as checked exceptions and runtime exception.

Errors – Errors can be defined as scenarios that are exceptional and it is difficult to recover from such scenarios such as a hardware failure or an out of memory error. The most two common types of errors are OutOfMemoryError and StackOverflowError.

Checked Exceptions – It is an exceptional scenario which could be anticipated in a program before trying to recover from it.

Runtime Exception – It occurs as a result of bad programming such as trying to retrieve an element from the Array. It is also defined as the Parent Class of all runtime exceptions.

Exception Methods that are of Significance

None of the specific methods are provided by the Exception and all its sub-classes. Furthermore base class Throwable defined almost all of the methods. The different types of exception scenarios are specified by means of creating the exception classes and this helps in easily identifying the root cause along with the ability to handle exception according to its type. For interoperability, serializable interface are implemented by Throwable class.

The most important methods of Throwable Class are as follows.

  • Public String getMessage()
  • Public String getLocalizedMessage()
  • Public Synchronized Throwable getCause()
  • Public String toString()
  • Public void printStackTrace()

Java 7 Automatic Resource Management and Catch Block Improvements

The catch block code appeared to be distorted whenever a lot of exceptions are catching within a single try block. The presence of redundant code in logging the error is yet another aspect that makes the catch block code look distorted. One of the key features in Java 7 is the presence of improved catch block that is capable of catching multiple exceptions within a single catch block. One of the improvement methods that could be used in Java 7 would be ‘try-with-resources’ which helps create a resource in the try statement and thereby make use of it within the ‘try-catch block’. The run time environment will then automatically close these resources whenever the execution comes out of try-catch block.

Creation of Custom Exception Classes

Even though Java offers a variety of exception classes for us to make use of, still there can be a circumstance wherein we will have to create our own custom exception classes so as to indicate the caller about the specific type of exception along with the accurate message and any other custom fields which we would likely introduce for tracking purposes. Error codes are among one of the examples.

Best Practices for Exception Handling

  1. Make use of Specific Exceptions – Useful information is not available with base classes of Exception Hierarchy. That is the main reason why Java is comprised of many exception classes. It is desirable to throw and catch specific exception classes which would help the caller to understand the root cause of exception easily and thereby process them. All this makes debugging quite easier and thereby help the exceptions to be properly handled by the client application.
  2. Throw Early or Fail-Fast – It is desirable to throw exceptions as early as possible. The actual location of the exception could be identified at the time of debugging by taking a close look at the stack carefully.
  3. Catch Late – The exceptions are catchable only when it could be handled properly as most of the developers tend to catch the exception and log the error.
  4. Closing Resources – All the resources should be closed as the exceptions could lead to halt of program processing. Therefore either Java 7 try-with-resources enhancement should be able to allow Java runtime close it or make use of block.
  5. Logging Exceptions – Helps the caller know why the exception had occurred. It is always desirable to avoid empty catch block that is not able to manage the exception and does not provide any meaningful details of the exception for debugging.
  6. Single Catch Block for Multiple Exceptions – Gives a cleaner image by reducing the code size.
  7. Make use of Custom Exceptions – Error code is used for creating custom exceptions and the error codes would be handled by a caller program. It is always better to create a utility method for processing different error codes and thereby use it.
  8. Naming Conventions and Packaging – Always ensure the custom exceptions ends with Exception so that the name itself should signify that it’s an exception.
  9. Exceptions are Costly – Not every time exceptions are required to throw exception and returning a Boolean variable itself is enough in indicating the caller program that an operation was successful or not.
Thrown Exceptions has to be documented – The exceptions thrown by the method could be clearly specified by making use of javadoc@throws and it could be of immense help whenever an interface is being provided to other applications for using
Exception can be defined as an error event that could occur during the execution of a program and it thus causes the normal flow to be disrupted. Java Exception Handling is offered by Java to handle such scenarios in an object-oriented and robust way. We will look in detail the various best practices on offer by Java Exception Handling.

Overview of Java Exception Handling

Even though no one would like to see exceptions occurring, users will have to deal with it in some or other manner. Java Exception Handling framework has been designed as robust and easy to use framework. There are several factors that might have contributed for the exceptions. The reasons could be failure of hardware, failure of the network connection, database server down or it can be because of wrong data being entered by the user.

Java creates an exception object whenever an error happens while executing a statement and thus leading to the stoppage of normal flow of program. JRE would then look in to someone who would be capable of handling the exception being raised. The exception object is comprised of a lot of debugging information ranging from method hierarchy, type of exception and the line number on which the exception actually occurred. If an exception object is created and is handed over to a Run-time Environment whenever an exception occurs in a method, then it is known as ‘throwing the exception’. The handler would be then identified for the exception and once identified the exception object would be then passed on to the handler for processing it. The handler is supposed to be performing process known as ‘Catching the Exception’.

Exception Handling Keywords

Specific keywords are offered by Java for exception handling purposes.

Throw - This keyword is used to throw exception to the run-time for handling it.

Throws – This keyword is used in method signature so as to allow the program to know the possibility of exceptions that might be likely thrown by the method. The exceptions would be handled by the caller method or it could be propagated to the caller method by making use of the throws keyword.

Try-catch – For exception handling in code, the try-catch block is usually used. Try signifies the start of the block where as Catch signifies the end of the try block when it comes to handling the exceptions. However it is necessary for a catch block to have a parameter that is of type Exception.

Finally – This keyword is optional and could be used only with try-catch block. Finally block could be used during instances wherein some resources would be open and does not get closed when exception halts the process of execution.

Exception Hierarchy

As we all know that exception object is created whenever any exception is being raised. Java exceptions are represented as hierarchical and different types of exceptions are categorized by making use of inheritance. The parent class of Java Exceptions Hierarchy is Throwable and it is usually comprised of two child objects namely Error and Exception. The exceptions however are further classified as checked exceptions and runtime exception.

Errors – Errors can be defined as scenarios that are exceptional and it is difficult to recover from such scenarios such as a hardware failure or an out of memory error. The most two common types of errors are OutOfMemoryError and StackOverflowError.

Checked Exceptions – It is an exceptional scenario which could be anticipated in a program before trying to recover from it.

Runtime Exception – It occurs as a result of bad programming such as trying to retrieve an element from the Array. It is also defined as the Parent Class of all runtime exceptions.

Exception Methods that are of Significance

None of the specific methods are provided by the Exception and all its sub-classes. Furthermore base class Throwable defined almost all of the methods. The different types of exception scenarios are specified by means of creating the exception classes and this helps in easily identifying the root cause along with the ability to handle exception according to its type. For interoperability, serializable interface are implemented by Throwable class.

The most important methods of Throwable Class are as follows.

  • Public String getMessage()
  • Public String getLocalizedMessage()
  • Public Synchronized Throwable getCause()
  • Public String toString()
  • Public void printStackTrace()


Java 7 Automatic Resource Management and Catch Block Improvements

The catch block code appeared to be distorted whenever a lot of exceptions are catching within a single try block. The presence of redundant code in logging the error is yet another aspect that makes the catch block code look distorted. One of the key features in Java 7 is the presence of improved catch block that is capable of catching multiple exceptions within a single catch block. One of the improvement methods that could be used in Java 7 would be ‘try-with-resources’ which helps create a resource in the try statement and thereby make use of it within the ‘try-catch block’. The run time environment will then automatically close these resources whenever the execution comes out of try-catch block.

Creation of Custom Exception Classes

Even though Java offers a variety of exception classes for us to make use of, still there can be a circumstance wherein we will have to create our own custom exception classes so as to indicate the caller about the specific type of exception along with the accurate message and any other custom fields which we would likely introduce for tracking purposes. Error codes are among one of the examples.

Best Practices for Exception Handling

  1. Make use of Specific Exceptions – Useful information is not available with base classes of Exception Hierarchy. That is the main reason why Java is comprised of many exception classes. It is desirable to throw and catch specific exception classes which would help the caller to understand the root cause of exception easily and thereby process them. All this makes debugging quite easier and thereby help the exceptions to be properly handled by the client application.
  2. Throw Early or Fail-Fast – It is desirable to throw exceptions as early as possible. The actual location of the exception could be identified at the time of debugging by taking a close look at the stack carefully.
  3. Catch Late – The exceptions are catchable only when it could be handled properly as most of the developers tend to catch the exception and log the error.
  4. Closing Resources – All the resources should be closed as the exceptions could lead to halt of program processing. Therefore either Java 7 try-with-resources enhancement should be able to allow Java runtime close it or make use of block.
  5. Logging Exceptions – Helps the caller know why the exception had occurred. It is always desirable to avoid empty catch block that is not able to manage the exception and does not provide any meaningful details of the exception for debugging.
  6. Single Catch Block for Multiple Exceptions – Gives a cleaner image by reducing the code size.
  7. Make use of Custom Exceptions – Error code is used for creating custom exceptions and the error codes would be handled by a caller program. It is always better to create a utility method for processing different error codes and thereby use it.
  8. Naming Conventions and Packaging – Always ensure the custom exceptions ends with Exception so that the name itself should signify that it’s an exception.
  9. Exceptions are Costly – Not every time exceptions are required to throw exception and returning a Boolean variable itself is enough in indicating the caller program that an operation was successful or not.
Thrown Exceptions has to be documented – The exceptions thrown by the method could be clearly specified by making use of javadoc@throws and it could be of immense help whenever an interface is being provided to other applications for using

This blog is listed under Development & Implementations Community

Post a Comment

Please notify me the replies via email.

Important:
  • We hope the conversations that take place on MyTechLogy.com will be constructive and thought-provoking.
  • To ensure the quality of the discussion, our moderators may review/edit the comments for clarity and relevance.
  • Comments that are promotional, mean-spirited, or off-topic may be deleted per the moderators' judgment.
You may also be interested in
 
Awards & Accolades for MyTechLogy
Winner of
REDHERRING
Top 100 Asia
Finalist at SiTF Awards 2014 under the category Best Social & Community Product
Finalist at HR Vendor of the Year 2015 Awards under the category Best Learning Management System
Finalist at HR Vendor of the Year 2015 Awards under the category Best Talent Management Software
Hidden Image Url

Back to Top