File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception

 
Arathi Rajashekar
Ranch Hand
Posts: 112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am bit confused. Tell me if a block of code doesnot throw any exception, its valid to enter in try and catch block right. But sometime back, when I wrote some code, it gave me compiler error, saying that it is not throwing any exception, so there is no need of try or catch block. It will be good if somebody explains me with code.
Thanks in advance
 
Shivaji Marathe
Ranch Hand
Posts: 203
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arathi :
I believe, the code you write inside
your try{} block must throw the kind of exception that you are catching in your catch block.
If you write

then the compiler will complain.
This is the message I get
Foo.java:9: Exception java.io.IOException is never thrown in the body of the corresponding try statement.
catch (IOException e){ // some exception catching code here
^
HTH
[ January 16, 2002: Message edited by: Shivaji Marathe ]
[ January 16, 2002: Message edited by: Shivaji Marathe ]
 
Jose Botella
Ranch Hand
Posts: 2120
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This rule doesn't apply for a non checked exception.
However an instance of Exception can be caught without being thrown.
 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Arathi Rajashekar:
Hi,
I am bit confused. Tell me if a block of code doesnot throw any exception, its valid to enter in try and catch block right. But sometime back, when I wrote some code, it gave me compiler error, saying that it is not throwing any exception, so there is no need of try or catch block. It will be good if somebody explains me with code.
Thanks in advance


If you catch an non-checked exception , without throwing it or calling/doing anything that can throw it in your try block then you will get a compile time error

However if the exception is non-checked like nullptr or class cast then it doesnt matter wheather you catch or not , it will still compile becoz the programmer is not obligated to do it at compile time
Ragu
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
that was a good point. i didn't know that.
regards
maulin
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic