Is it safe to implement business logic inside a catch block? - android

I want to update a shared preference and ImageView(using setImageResource) inside a catch block. But is is safe to do so?
try{
//do something
} catch (Exception e) [
Log.d("TAG", "Exception " + e);
sharedPref.edit().putString("Value", "no_value").apply();
myimageview.setImageResource(resid);
}

It's ok to do that. Actually there is no another way to execute code when some exception happen. Of course it is better if you know the type of exception (for example null pointer) and to use something like:
if(something != null){
// normal logic
}else{
// exception logic
}

Related

How to properly resolve conflict during azure synchronization from android?

I'm in trouble with azure synchronization, I'm able to detect the number of pending operations by mCLient.getSyncContext().getPendingOperations(); but can't resolve them. Any help or suggestion?
When working with in an offline scenario and you have pending operations, you can push them to the server by using the push() function.
It would look something like the following:
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
syncContext.push().get();
// here you would do a pull on any table you want to grab data from
}
catch (final MobileServiceConflictException e)
{
// the server item causing the exception can be obtained by calling e.getItem()
JsonObject serverObject = e.getItem();
// on the sync context, call one of the following:
// .cancelAndDiscardItem() to cancel update and discard local item
// .cancelAndUpdateItem() to update the local item with the server's copy
// .cancelAndUpdateItem(JsonObject item) to update the server's item w/ the local
// make sure to call push() again on the sync context
}
All in all - make sure you call push() on the MobileServiceSyncContext and then handle any MobileServiceConflictException that may return.
If I catch for MobileServiceConflictException android studio tells me that the Exception is never thrown in this corresponding try block.
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
syncContext.push().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (MobileServiceConflictException e) {
}

catch only ENOSPC on Android

This might be a basic question but I cannot find an answer. When you want to catch only FileNotFound in Android, then you write
} catch (FileNotFoundException e) {
But what do you write if you want to catch exactly ENOSPC (No space left on device) errors? I can't use "catch (Exception e)" because I want to explicitly deal with this one error.
You cannot do so directly as enospc is signaled as a java.io.IOException which will catch many other io related issues as well. But by looking up the cause and the error it's signalling you can zoom in and handle enospc exceptions but rethrow all others, like this:
} catch (IOException ex) {
boolean itsanenospcex = false;
// make sure the cause is an ErrnoException
if (ex.getCause() instanceof android.system.ErrnoException) {
// if so, we can get to the causing errno
int errno = ((android.system.ErrnoException) ex.getCause()).errno;
// and check for the appropriate value
itsanenospcex = errno == OsConstants.ENOSPC;
}
if (itsanenospcex) {
// handle it
} else {
// if it's any other ioexception, rethrow it
throw ex;
}
}
Sidenote: } catch (Exception e) { is generally considered bad practice.

smack error when trying to login on server

public void login() {
try {
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Yey! We're connected to the XMPP server!");
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
Log.i("login fuction","login error");
e.printStackTrace();
}
}
[eclipse error log]
I'm getting an error at this stage after successful connection to the server
i don't have the privilege to comment but from the input that you have given here the error possibly lies in the login function that is throwing the null point exception
Possible cases
1) When you call instance method on a null object. you won't get null pointer exception if you call static method or class method on null object because static method doesn't require an instance to call any method.
2) While accessing or changing any variable or field on null object.
3) Throwing null when an Exception is expected to throw.
4) When calling length of array when array is null.
5) Accessing or changing slots of null just like an array.
6) When you try to synchronize on null object or using null inside synchronized block in Java
give the code for login function for further help
Hope this helps you
Which server are you calling? If you are calling gtalk or fchat, those have stopped using xmpp. You may search in Google to find out. And if you plan to connect to you own ip server, please use xmpptc. It would be nice if you could give some more of your code.
I've finally found the solution, i had to add smack-java7 in my dependencies

How do i display the catch exception?

I just want to ask how do i display the catch exception in android so that i will know if my application catching some error..
example on this.
try {
my codes here.....
} catch (IOException e) {
//how do i dpslay the exception
}
Thank you in advance.
I guess you want some visual (UI) representation of errors.
You can display your errors with Toast, for example.
Or use some library like Crouton. See http://johnkil.github.io/Android-AppMsg/
you can use:
try {
// my codes here.....
} catch(IOException e){
Log.d("MY_APP", "---------------------"); //separator from other logs (optional)
e.printStackTrace();
Log.d("MY_APP", "---------------------"); //separator from other logs (optional)
}
You can use Toast class for instance:
...
catch (IOException e) {
Toast.makeText(<context>, e.getMessage(), Toast.LENGHT_LONG).show();
// or use Log class like Log.e("From class X", e.getMessage());
}
Note if that piece of code is invoked from background Thread you cannot show that message for that that Thread.
In this scenario you need to use another mechanism (runOnUiThread(), Handler, AsyncTask, etc.).
Try doing this...This might help you..
try {
my codes here.....
} catch (IOException e) {
Log.e("e", "exception", e);
}

Need to move from try block to catch

I have written some code in the try block as follows.
try {
if (server1IPAddress != "") {
if ( InetAddress.getByName(server1IPAddress).isReachable(1000) == false) {
}
InsertUploadedTrancasctionDetails(server1IPAddress, deviceId,
XMLTransactionData);
}
} catch (Exception exception) {
if ((server1IPAddress != server2IPAddress)
&& (server2IPAddress != "")) {
InsertUploadedTrancasctionDetails(server2IPAddress, deviceId,
XMLTransactionData);
}
when we are not able to reach an IP Address i need to move from try block if condtion to catch block ie when IP address reachable is false.
if ( InetAddress.getByName(server1IPAddress).isReachable(1000) == false) {
}
I am not able to make an exception in the if block.
Is there any way to move from the If block to the catch block without making an exception or by making an exception in the if block.
Will any one help me please.
If the code for the not-reachable condition is the same as the code in the exception block, then you should either throw an exception, or refactor the current catch code into a method, and call that method from both locations. (Or just repeat the code, but ew.) I'm not really sure what the problem is.
FWIW, checking explicitly against false is generally frowned upon--negate the condition instead:
if (!InetAddress.getByName(server1IPAddress).isReachable(1000)) {
// Call refactored catch-handling code, or throw exception.
}
Catching Exception, particularly if not logging it, is an anti-pattern, although if you're wrapping it and/or re-throwing it, it's not as bad.

Categories

Resources