• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

About throws in exceptions

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi frnds,
can anybody tell me about throws clouse in methods like
public void myMethod(Myobj ob) throws IOException
{ }
thanx
 
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
IOException is a checked Exception. This means that the method performing any IO or call any such operation that might throw IOException must be handled in the method. This is the requirement of Java Compiler. But this method instead of handling the exception generated in its body passes the responsibity to the caller of the method. This is done by declaring in the method declaration as throws IOException.
The following means that myMethod() might throw IOException but this method would not handle it and the onus lies on the caller of this method to handle it. For example :
1. main method calls meth1().
2. meth1 calls meth2().
3. meth3() calls myMethod().
Then it is the responsibility of the meth2() to handle IOException. Now again meth2() may decide not to handle this IOException and declares in the declaration that it throws IOException. And when even main also declares that it throws IOException then the JVM executes the uncaught exception and exits the program.
public void myMethod(Myobj ob) throws IOException
{ }

The following could be some of the scenarios :
I) JVM handling the exception :
class Checked
{
public static void main (String[]args) throws IOException{
Checked c = new Checked();
c.meth1();
}
public void meth1() throws IOException
{
meth2();
}
public void meth2()throws IOException
{
myMethod();
}
public void myMethod() throws IOException
{}

II) myMethod handling its own exceptions
public void myMethod ()
{
try
{
....
}
catch (IOException e) {}
}
In the second case the normal execution of codes resumes after the catch block is executed where as in the first case, the program terminates abnormally.
Hope this has been helpful and not confusing ...
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic