Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What kind posible exception thrown

 
Ahamed Ali
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I would like to know, this code throws which kind of exceptions.

class X
{
private Vector objects = new Vector();

public void compute ()
{
Iterator iter = objects.iterator();
while (iter.hasNext()) {
try {
Object o = (Object)iter.next();
System.out.println(o.hashCode());
}
catch (Exception ex) {
// under which circumstances will which Exceptions
// be caught here ?
}
}
}

public void addObject (Object o)
{
objects.add(o);
}
}


Thanks in advance
 
M Beck
Ranch Hand
Posts: 323
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
one (crude, but functional) way to find out is to remove the "catch" statement and block, replace it with an empty "finally" statement/block, and try to compile the code. it will not compile, but the compiler will give errors for any checked exceptions that might arise from the "try" block. reading those errors will tell you what you need to worry about, at minimum.

...of course, there's still the possibility of unchecked exceptions being thrown. you'll have to read the documentation for any methods and classes you make use of inside the "try" block to learn about those.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic