File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceptions error

 
Shiva Mohan
Ranch Hand
Posts: 484
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Any Checked exceptions can't be thrown without declaring a method or within a catch clause to handle it.Here we declared Exception is a parentclass and
IOException and SQLException are subclasses of Exception.Then why the error "SQLException is not thrown in try block" at line1 is coming.I don't get that.Please help me.
 
anil kumar
Ranch Hand
Posts: 447
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

try {
throw new IOException();//line 1
} catch (IOException e) {
throw new SQLException();
} catch(SQLException e)//line 2 {
//---------------showin error at line1throw new InstantiationException();
}
At line 1 you are throwing IOException and at line 2 you are trying to catch SQLException.They don't have any relation ship.
here at line 1 you are throwing IOException means you can catch either IOException or subclass of that one.
i think you got it
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shiv Mohan,



You place the method call of code statements that may throw certain exception in the try block and then place catch block followed by that to handle that exception. If inside the try block the checked exception is not thrown, and you put catch block to handle that exception, compiler complaints that "are you sure you are doing write; there is nothing like SQLException in the try block, so for what you are handling that". Hence compilation error.

If you throw any checked exception in the catch block too, that exception must either be in the try catch block or declared to be thrown by the method. catch block placed to handle try block code never goes to handle exceptions generated in the catch block itself. That is what, as I see the matter of confusion to you. Is that right?

Thanks and Regards,
cmbhatt
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic