Correct try/catch usage - android

Can someone please explain to me the proper usage of try/catch when accessing an Android database? Android Studio forces you to use it whenever you are opening a database for writing. I understanding the purpose of using it but my question is would it better do include all of my database work in the try clause like this?
try {
db.open();
db.delete(item);
db.add(item);
/////......
} catch (SQLException e) {
e.printStackTrace();
}
db.close()
Or is it better to use it like this?
try {
db.open();
} catch (SQLException e) {
e.printStackTrace();
}
db.delete(item);
db.add(item);
/////......
db.close()
Is there an important difference? Is one way more efficient or safer than the other?
Thanks in advance for your responses!

Look at the documentation and only use try / catch on methods that throw exceptions

You use the catch block to actually catch exceptions which can be thrown from your code (during runtime). So every call which can throw an exception should be tried/catched, because it helps you differentiating, what went wrong with your code.
So: Wrap a try catch around every function call which can throw an exception

in your second example, if your delete query is malformed, you won't know, the program will continue to run thinking it's been successful.
A try catch, tries something, then catches any errors which may arise.

Related

How to Clear Database in Realm in Android

I want to clear whole database when a user press logout button and loads a new data when another user login.I tried many solutions like
try {
Realm.deleteRealm(realmConfiguration);
} catch (Exception ex){
throw ex;
}
Also
try {
Realm.deleteRealmFile(getActivity());
//Realm file has been deleted.
} catch (Exception ex){
ex.printStackTrace();
//No Realm file to remove.
}
But neither of the code works.
Thanks in advance.
When you call Realm.deleteRealm(), you have to make sure all the Realm instances are closed, otherwise an exception will be thrown without deleting anything. By calling this method, all Realm files are deleted, which means all objects & schemas are gone. Catching all exceptions is a bad practise for any general cases.
Or you can call Realm.delelteAll() in a transaction block. This doesn't require all Realm instances closed. It will just delete all the objects in the Realm without clearing the schemas. And again, don't catch all exceptions.
If you are sure there are not any other databases you want to save, you can delete all the other data also. you can follow this answer
Clear Application's Data Programmatically

Two Asynctasks following each other

I am having trouble working with asynctasks. The problem is that I need data from one asynctask to be loaded into a static variable before another asynctask begins since asynctask2 needs that static variable. I tried using this code to stall asynctask2 but it doesn't even show up in my log cat:
//geocode is the first asynctask
while(geocode.getStatus().equals(android.os.AsyncTask.Status.PENDING))
{try {;
wait(100);
Log.i("waiting", "waiting");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
use the onPostExecute of the first AsyncTask to start the next one, that way you know it has finished and it is safe to start the next one. I would however try to think of a better way to accomplish what you are trying to do

How to handle SQLiteException in Android activity?

I am looking at how to handle exceptions in Android.
In the update() function in the sample code for the Notepad Content Provider, it calls getWriteableDatabase(), which can potentially throw an SQLiteException.
I notice that the NoteEditor Activity saveNote() function has the following code:
// Commit all of our changes to persistent storage. When the update completes
// the content provider will notify the cursor of the change, which will
// cause the UI to be updated.
try {
getContentResolver().update(mUri, values, null, null);
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage());
}
What happens if an SQLiteException occurs?. I want to be able to catch this exception in the Activity and display an appropriate message to the user (via a toast or something similar).
I thought I could do by adding an extra catch for SQLiteException. However, I read the following info in the Google docs:
"Remember that the Android system must be able to communicate the Exception across process boundaries. Android can do this for the following exceptions that may be useful in >handling query errors:
IllegalArgumentException (You may choose to throw this if your provider receives an >invalid content URI)
NullPointerException"
So I am now confused - can I catch the SQLiteException or not?
Whenever possible, you should catch the Exception in the class or component in which the Exception occurred. Use some sort of broadcast mechanism or return value semantics to report errors across processes.
It's admittedly a tricky situation. Some people say that if an SQLite (or other Exception) occurs in a ContentProvider, the provider should propagate the exception upwards instead of returning null in the Cursor. However, this generally won't work across processes! On the other hand, returning null doesn't give you a lot of information.
A limited set of Exceptions do traverse process boundaries, but SQLiteException isn't among them - still they might be useful/appropriate.

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();
}
}
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.
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.

Android - try/catch question

i have a try/catch in a function that returns a value. if all goes well the return statement in the try block works fine. but what am i supposed to do if theres an exception? what do i return in the catch and finally blocks? the return statement has to be there or the code doesnt compile.
edit: in 1 function i connect to a URL, read a file, and return a string. in another function i open an image from the internet and return a bitmap. so in both of these cases, what am i supposed to have in the return statement at the catch and finally blocks?
One of the following:
Return a special value that indicates an error to the calling code.
Return a default value (depending on your context, there may not be a good one).
Don't catch the exception, instead add a throws to the header.
Catch the exception, do the cleanup, and rethrow the exception.
In general, there's no escaping the fact that the function can error out. The calling code must either be notified of that, or the function must effectively swallow an error and pretend nothing bad happened; that involves returning something. The specifics depend on your context...
The value you return should be able to represent an error, for example, null should mean the function didn't work. So, in the catch block, the function would return null, for example. In the finally block, you should free any resource you used (for example, close any files you opened, etc).
You put those things in the finally block because it's guaranteed that it will be ran sometime, even if the code in your catch block throws an unhandled exception or anything. And it will also run if the function worked just as wanted.
Use return null; this statement outside your try/catch block. If the things work, your try block will execute and will return , if it fails because of exception, it will be caught and you will see error.

Categories

Resources