Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Exceptions  RSS feed

 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can someone please tell me why the following code snippet is illegal AND what is the correction to be made ?



I tried making a full program using 'ArithmeticException' instead of IO, as shown below and it compiles. However, when i put IOException in place of ArithmeticException in the above program, i get a compile-time error.



Please help me to understand what is happening here ?
Regards..rsb

PS : How do i present/format my code on this website the way an IDE does it ?

 
Campbell Ritchie
Marshal
Posts: 55698
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rahul Sudip Bose wrote: . . . How do i present/format my code on this website the way an IDE does it ?
By indenting it correctly, using spaces, not tabs. Don't write caode as if you were writing a letter, but as I showed here.
 
Campbell Ritchie
Marshal
Posts: 55698
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please tell us the details; what sort of code did you have in your blocks? Which compiler error did you suffer? In the cases of Exceptions, they are usually informative. And have a look at the Java™ Tutorials, particularly the section about "catch or specify requirement".
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're getting the error, "cannot find symbol" for "IOException," then it's probably because you're missing an import statement, since IOException is in the package java.io. This error would NOT apply to ArithmeticException, because ArtihmeticException is in java.lang, which is automatically imported.

Beyond that, I would also expect the error, "unreported exception java.io.IOException..." This is because you are explicitly throwing an Exception in your catch block, but not handing it (re-catching it or declaring it) elsewhere. This error would NOT apply to ArithmeticException because ArithmeticException is a subclass of RuntimeException, which is "unchecked" (meaning the complier does not require handling for it).

I would also expect the error, "exception java.io.IOException is never thrown in body of corresponding try statement." This is because the compiler is smart enough to know that nothing in your try block can throw an IOException. I'm not sure why the compiler doesn't do the same for ArithmeticException. It might be because ArithmeticException is unchecked. On the other hand, I'm not sure this check is comprehensive, so... I don't know.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!