48321

Exception handling as per java coding standards

i have one query regarding java standards in case of exception handling.

code snippet:

public String methodXXX(){ //This method may throw IllegalArgumentexception and arrayoutofboundaryException. }

In this case, Which is good coding standard and please let me know why case1:

public String methodXXX() throw IllegalArgumentexception,ArrayoutofBoundaryException.{ //This method may throw IllegalArgumentexception and arrayoutofboundaryException. }

case2:

public String methodXXX()throws Exception{ //This method may throw IllegalArgumentexception and arrayoutofboundaryException. }

Why i am mentioning case2 here is: we might not expect there can be other exception can occur, while run time. As Exception is parent class for all exceptions, case 2 is preferable ??? If yes, in which cases case1 is feasible? Can u please explain me performance point of you also?

Answer1:

It's always much better to declare the specific exceptions a method throws. This not only makes it clearer what possible problems might occur, but it makes it easier to handle them separately if necessary.

There aren't really any performance ramifications: creating the stack trace for an exception is such an expensive operation that it dwarfs all other considerations.

Answer2:

Both exceptions are RuntimeException subclasses, you don't have to explicitly declare them in the throws part of the method declaration.

In Java there are two kinds of exceptions: checked and unchecked. As explained in the link, each one is used in different circumstances. All exceptions which are subclasses of RuntimeException are unchecked exceptions, and in general you're not supposed to declare that a method throws them.

Answer3:

Typically, RuntimeExceptions like IllegalArgumentException and ArrayIndexOutOfBoundsException reflect programmer error, as opposed to an exception that the final program should know how to handle at runtime.

Generally, it's not worth explicitly declaring RuntimeExceptions, since the proper way to respond to such an exception is usually to just throw up, so the programmer who's running the program knows that there's a bug that needs fixing, and can get the stack trace. It's not usually a good idea to write a try/catch that catches a RuntimeException, so there's no point.

With regards to other kinds of Exceptions, you should declare the specific exceptions that might be thrown, so that users of your method can catch each of them individually and write different responses to each of the specific exception types. Just declaring that you're throwing Exception forces users of your method to write exception handlers that can't do anything intelligent, since they don't know anything about the specific exception that was thrown.

Answer4:

I think you should not throw exception instead put it in the java doc comment. This way user of your api is aware of what kind of exception can happend and is not forced to capture those exceptions.

/** * @throws IllegalArgumentexception * @throws ArrayoutofBoundaryException */ public String methodXXX() { //This method may throw IllegalArgumentexception and arrayoutofboundaryException. }

I prefer Runtime Exception over checked exception, as most cases forcing to catch exception wont help much. So putting all the exceptions in the java doc make it clear also as well as wont force to catch it. This way the code is cleaner and chances of propagation of exception to top layers is there by default. Else I have seen many developers just catch the checked exception and dont do any thing, leaving top layers un-aware of any exception happening the lower layers.

General thumb of rule is 'If user can recover from exception throw checked exception else document run time exception' And even then I prefer the latter as check exception are generally not very helpful.

Recommend

  • what is for…in statement in javascript
  • GData Youtube : obtaining thumbnails
  • Cache is client side or server side?
  • UITableView Multiselect in MonoTouch
  • Stack size of secondary threads, significant differences between DEBUG and RELEASE versions
  • What are “Java EE 7 API Library” and “Java EE Web 7 API Library” and when to use them?
  • Data binding in Polmyer's
  • Create recursive binary tree?
  • WPF: Resize item size to have all items visible
  • Exception handling as per java coding standards
  • Measure heap used by each object in Java [closed]
  • .NET Core 2.0 RSA PlatformNotSupportedException
  • Flot returns incorrect x value (mm/dd/yy - date) after zoom for stack bar chart
  • joomla! 1.5.26 and “You are currently logged in to the private area of this site”
  • Can't find cygwin setup.exe file?
  • numpy 64bit support in PTVS and numpy System.Int64 casting
  • CUDA NSight is not installed with CUDA 5.0 installation file on Windows 8? [closed]
  • How to run bash commands like “npm install” on complie
  • Whats the right place for testhelper-classes? (phpunit/best practise)
  • Show records ordered with maximum price first in PHP & MySQL
  • unrecognized selector isPitched called
  • Python: Split a String Field into 3 Separate Fields using Lambda
  • maven jboss-as:start A required class was missing … org/sonaty…/ArtifactResolutionException
  • Is there a way to call library thread-local init/cleanup on thread creation/destruction?
  • SQL query to group by maximal sets of a column having inner consecutive distances below a threshold
  • How do I add a File Type Association in a Windows Phone 8.1 app manifest?
  • Where these are stored?
  • Cannot upload to OneDrive using the new SDK
  • Graphics.CopyFromScreen [Web application] + The handle is invalid
  • Calling Worksheet functions from vba in foreign language versions of Excel
  • Display images in Django
  • Problem deserializing objects from cache on MyBatis 3/Java
  • Django rest serializer Breaks when data exists
  • How to rebase a series of branches?
  • Initializer list vs. initialization method
  • Control modification in presentation layer
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Azure Cloud Service Web Role web pages do not load
  • Fetching methods from BroadcastReceiver to update UI
  • what is the difference between the asp.net mvc application and asp.net web application