rena-c
rena-c

Reputation: 325

try catch statement in java lang

i have a statement like this that gives an error "missing return statement".But i assigned return statements as you see.whats wrong?

public int compareTo (Object o)
{
    try 
      {
          Sports m = (Sports)o;
          if(this.date.before(m.date)&& o instanceof x)
          {
             return -1;
          }
          else if(this.date.equals(m.date)&& o instanceof x)
          {
            return 0;
          }
          else
          { 
            return 1;
          }
    }

    catch(IllegalArgumentException e) 

    {
        System.out.print("Not an instance of x class");
    }
}

Upvotes: 0

Views: 2508

Answers (4)

amukhachov
amukhachov

Reputation: 5900

this.date.before(m.date)

it's the only piece of code which could generate IllegalArgumentException. Are you sure that you want to catch it? If you just want to be sure o is instance of x do smth like:

public int compareTo (Object o){
if(o instanceof x) {
    Sports m = (Sports)o;
    if(this.date.before(m.date)&& o instanceof x)
        return -1;
    else if(this.date.equals(m.date)&& o instanceof x)
        return 0;
    else 
        return 1;
}
else {
    System.out.print("Not an instance of x class");
    return 2; 
}

}

Upvotes: 0

Ravi Parekh
Ravi Parekh

Reputation: 5622

if u want to use catch

int returnResult = -99;
try{

        returnResult = -1 ;
         else 
        returnResult = 0;
         else 
        returnResult = 1;
 }   catch(IllegalArgumentException e) {
    System.out.print("Not an instance of x class");
}
return returnResult;

Upvotes: 2

Mike Thomsen
Mike Thomsen

Reputation: 37526

It's raising a compiler issue because there is a scenario with no return: when an exception is thrown. You need to add a return statement after the catch if you're really going to catch IllegalArgumentException.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503859

Yes - if IllegalArgumentException is caught, you're not returning anything.

To be honest, it's very rarely a good idea to catch IllegalArgumentException. Why are you catching it here?

Upvotes: 5

Related Questions