• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method declaring and catching exception  RSS feed

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Usually when a method declares exception, calling method is the one which has to catch exception. But can a method declare and throw exception at the same time ? I don't think its required to declare that method throws an exception, if it handles the exception But this is a hypothetical question. I will test it by myself, but are there any issues involved in this ?

Thanks
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nirjari patel wrote:Usually when a method declares exception, calling method is the one which has to catch exception. But can a method declare and throw exception at the same time ? I don't think its required to declare that method throws an exception, if it handles the exception But this is a hypothetical question. I will test it by myself, but are there any issues involved in this ?

Thanks



I would recommend that when you test it, that you test it with checked exceptions.

Henry
 
smlsriram Srinivasan
Greenhorn
Posts: 2
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

First for your question, yes. A method can throw as well as catch and it depends on the where the exception is in its scope and the business logic it uses.


1. A method can handle as many exceptions that are created in its logic and throws those which cannot be handled by it. For example, read() methods in InputStream methods throw IOException because that this is not in its scope and cannot do anything about it.

2. Sometimes especially in web tier applications, a user defined generic exception related to business logic will be created and if any exception occurs in the database or business layer, the methods will handle the generated java exceptions and throws the user defined exception. This is useful because in the UI layer, most times, user will expect to know whats the result (some generic information) and not the actual exception happened (Nullpointer or SQLEception).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!