ahmet
ahmet

Reputation: 734

Android Throw Exception

In my application, I use SQLiteOpenHelper class and it has insertOrThrow method. I want to learn that will this method close my connection before throw an exception? And it is written on definition of method that "the row ID of the newly inserted row, or -1 if an error occurred "

When throw an exception how it has a return value? Something is wrong. Explanation or throw ?

This is how I use InsertOrThrow. I want to know when I declare throws Exception to my method, is it necessary to use try-catch (If I don't have any special thing to do in catch like my exp.)?

public long insert(ContentValues cv) throws Exception {
    try
    {
        long rowId = getWritableDatabase().insertOrThrow(_tableName, null, cv);
        return rowId;
    }
    catch (Exception ex) {
        throw ex;
    }
    finally{
        Close();
    }
}

Upvotes: 2

Views: 13140

Answers (2)

theapache64
theapache64

Reputation: 11734

When throw an exception how it has a return value? Something is wrong.

Yes, you're right. The documentation seems wrong.

insertOrThrow doesn't return -1 , instead, it will throw SQLException if the query failed. There's a another method called insert which would return -1 if the query failed, and newly created rowID if success.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160170

It depends; if this.Close() can throw an exception, then it still needs to be declared as being thrown, or caught. Often times this is wrapped up in a small utility method.

It's not mandatory to use a catch, you can simply try/finally.

Regarding return values: methods that exit due to an exception don't have a return value.

Exceptions should encapsulate enough information to either:

  • allow the caller to do something useful with the exception, e.g., retry the operation, or
  • assist the developer in understanding the problem and lead him/her to a resolution.

I'd encourage you to follow standard Java naming conventions to avoid confusing readers of your code: non-final variables should begin with a lower-case letter. Method names should also begin with lower-case letters.

Also, you do not need to preface methods (or variables) with this when there is no need to disambiguate the property you're accessing.

Upvotes: 1

Related Questions