Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

when it is required to handle exception inside the function ?

 
Soumya Padhiary
Greenhorn
Posts: 20
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When it is required to handle exception inside the same function(where exception arised) and inside the calling place ?
case 1:
class Excp{
void func()
{
...........
try{
.........
......... //Exception arised
.........
}catch(Exception e)
{}
.........
}
main(...){
Excp e=new Excp();
e.func();
}}

case 2:
class Excp{
void func()
{
..........
.......... //Exception arised
..........
}
main(.....){
Excp e=new Excp();
try{
e.func();
}catch()
{}
}}

Can any one tell me in which situation we go for case 1 and case 2 ?

Appreciation in advance .
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64824
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Under no circumstances should you ever have an empty catch block. Never. Even if you need to "eat" the exception under rare circumstances, there should be a long comment explaining why there is an empty catch block.

But to answer the general question, you only catch an exception at a level that you have something useful to do with it.
 
Campbell Ritchie
Sheriff
Posts: 48910
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or, to give the another answer to your original question: never.

If you throw any Exception in any method, you should pass that back to the calling method as a signal that something has gone wrong. Throwing an Exception and catching it in the same method is simply an expensive way to write if‑else.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic