Android Studio keeps complaining ( lightbulb red X ) that 'db' and 'dbh' may not be instantiated in the finally
block.
So three things:
- If the insert fails, what is the state of
dbh
anddb
in the catch block, or the finally block? - More generally, what do I need to account for in the
finally
andcatch
blocks - Is lowering the complaint level in Android Studio the proper way to handle this :) ?
Below is the code. Its an Android AsyncTask.
@Override
protected Void doInBackground(Void... voids) {
SweepDatabaseHelper dbh;
SQLiteDatabase db;
try{
Random generator = new Random();
float freqstep = (stopFreq - startFreq)/steps;
dbh = new SweepDatabaseHelper(context);
db = dbh.getWritableDatabase();
// empty the table
db.delete(dbh.TABLE_SWEEPDATA, null, null);
// start writing the data
for(int i=0;i<steps;i++){
ContentValues values = new ContentValues();
SweepData sdata=new SweepData( (long)i, startFreq+(i*freqstep), (float)generator.nextFloat()*10 );
values.put(dbh.COLUMN_ID, (long)i);
values.put(dbh.COLUMN_FREQ, startFreq+(i*freqstep));
values.put(dbh.COLUMN_VSWR, sdata.getVswr());
db.insert(dbh.TABLE_SWEEPDATA, null, values);
publishProgress(new SweepData[]{sdata});
}
dbh.close();
return null;
}catch(Exception e){
// Do nothing at the moment
return null;
}finally{
if(db != null && dbh != null && db.isOpen()){
db.close();
}
}
}